@jskit-ai/auth-core 0.2.26 → 0.2.28

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/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - One-time pass sign-in: `./server/passSignIn` exports `signPass` (for the issuer, which holds an Ed25519 private key), `verifyPass` and `resolvePassSignInFromEnv`. A pass is a compact JWS (`alg` EdDSA, `typ` `pass+jwt`) naming one person (`sub`), one application (`aud`), one resource (`resource`) and its id (`jti`), lasting 60 seconds by default and at most five minutes. `AUTH_PASS_PUBLIC_KEY` (PEM, or base64 DER on one line) turns it on, with `AUTH_PASS_AUDIENCE` and `AUTH_PASS_RESOURCE` required. A refused pass is a 401 coded `auth.pass.malformed`, `auth.pass.badSignature`, `auth.pass.wrongAudience`, `auth.pass.wrongResource`, `auth.pass.expired` or `auth.pass.replayed`, or a 403 `auth.pass.unmapped`, each with an English text in `locales/en.json`. `AUTH_PATHS.LOGIN_PASS` is `/api/login/pass`, and the auth service gains the optional `signInWithPass({ pass })`.
5
6
  - `AUTH_COOKIE_SAME_SITE` sets the CSRF cookie's SameSite: `lax` (the default, unset or blank) or `strict`, as local auth's cookies take it; any other value stops the auth policy's startup with `AUTH_COOKIE_SAME_SITE must be lax or strict, not "<value>".` `./server/utils` exports `resolveAuthCookieSameSite(env)`, which reads it. Applications that leave it unset are unchanged.
6
7
 
7
8
  - **Second factor.** A route asks for one with the kernel's `secondFactor` option (`true`, or `{ maxAgeSeconds }` for a dangerous action), and the auth policy enforces it: a signed-in session that has not proved its second factor, or proved it longer ago than `maxAgeSeconds`, is refused with 403 `auth.secondFactor.required` (params `{ maxAgeSeconds }` when the route names one), checked after the CSRF token, the sign-in and the route's permission. The policy sets `request.secondFactorAt`, when the session last proved it (`""` when it has not), from the provider's `authenticate` result. `./server/secondFactor` gives `requireSecondFactor(request, requirement)`, the same refusal for an action whose requirement depends on more than its route (the actor's role, say; a call without a request, as from the server's own code, is refused too), with `isSecondFactorMet()` and `secondFactorRequiredParams()`; `./shared/authSecondFactor` gives `SECOND_FACTOR_REQUIRED` and `isSecondFactorRequired(error)` for clients.
package/locales/en.json CHANGED
@@ -65,6 +65,15 @@
65
65
  "password": {
66
66
  "updatedSignIn": "Password updated. Sign in with your new password."
67
67
  },
68
+ "pass": {
69
+ "malformed": "This sign-in pass is not a valid pass.",
70
+ "badSignature": "This sign-in pass was not signed by the trusted issuer.",
71
+ "expired": "This sign-in pass has expired. Open the app again from where you came.",
72
+ "wrongAudience": "This sign-in pass is for another application.",
73
+ "wrongResource": "This sign-in pass is for another resource.",
74
+ "replayed": "This sign-in pass was already used. Open the app again from where you came.",
75
+ "unmapped": "This sign-in pass names a person who has no account here."
76
+ },
68
77
  "denied": {
69
78
  "notAllowlisted": "Sign-in succeeded, but this account is not allowed to access this application.",
70
79
  "blocked": "Sign-in succeeded, but this account has been blocked from accessing this application.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-core",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -20,6 +20,7 @@
20
20
  "./server/authTexts": "./src/server/authTexts.js",
21
21
  "./server/booleanFlag": "./src/server/booleanFlag.js",
22
22
  "./server/devAuth": "./src/server/devAuth.js",
23
+ "./server/passSignIn": "./src/server/passSignIn.js",
23
24
  "./server/secondFactor": "./src/server/secondFactor.js",
24
25
  "./server/deferredAuthService": "./src/server/deferredAuthService.js",
25
26
  "./server/unsupportedOperation": "./src/server/unsupportedOperation.js",
@@ -128,6 +129,10 @@
128
129
  "subpath": "./server",
129
130
  "summary": "Exports server auth access, shared auth action, and Fastify auth policy providers plus server auth utility modules."
130
131
  },
132
+ {
133
+ "subpath": "./server/passSignIn",
134
+ "summary": "One-time signed passes: signPass for the issuer's server (Ed25519, one person, one audience, one resource, about 60 seconds), verifyPass for the application, and resolvePassSignInFromEnv, which reads AUTH_PASS_PUBLIC_KEY, AUTH_PASS_AUDIENCE and AUTH_PASS_RESOURCE."
135
+ },
131
136
  {
132
137
  "subpath": "./shared",
133
138
  "summary": "Exports shared auth client helpers (createApi and runAuthSignOutFlow), with structured subpaths at ./shared/authApi and ./shared/signOutFlow."
@@ -147,6 +152,6 @@
147
152
  }
148
153
  },
149
154
  "peerDependencies": {
150
- "@jskit-ai/kernel": "0.2.25"
155
+ "@jskit-ai/kernel": "0.2.26"
151
156
  }
152
157
  }
@@ -16,7 +16,15 @@ const AUTH_TEXTS = Object.freeze({
16
16
  devUserNotFound: Object.freeze({ status: 400, code: "auth.dev.userNotFound" }),
17
17
  displayNameRequired: Object.freeze({ status: 400, code: "auth.profile.displayNameRequired" }),
18
18
  recoveryTokenRequired: Object.freeze({ status: 400, code: "auth.recovery.tokenRequired" }),
19
- passwordUpdatedSignIn: Object.freeze({ code: "auth.password.updatedSignIn" })
19
+ passwordUpdatedSignIn: Object.freeze({ code: "auth.password.updatedSignIn" }),
20
+ // A one-time sign-in pass that was refused (passSignIn.js), one entry per reason.
21
+ passMalformed: Object.freeze({ status: 401, code: "auth.pass.malformed" }),
22
+ passBadSignature: Object.freeze({ status: 401, code: "auth.pass.badSignature" }),
23
+ passExpired: Object.freeze({ status: 401, code: "auth.pass.expired" }),
24
+ passWrongAudience: Object.freeze({ status: 401, code: "auth.pass.wrongAudience" }),
25
+ passWrongResource: Object.freeze({ status: 401, code: "auth.pass.wrongResource" }),
26
+ passReplayed: Object.freeze({ status: 401, code: "auth.pass.replayed" }),
27
+ passUnmapped: Object.freeze({ status: 403, code: "auth.pass.unmapped" })
20
28
  });
21
29
 
22
30
  function authText({ code } = {}, params = {}) {
@@ -0,0 +1,196 @@
1
+ import { createPublicKey, randomBytes, sign, verify } from "node:crypto";
2
+ import { AUTH_TEXTS, createAuthError } from "./authTexts.js";
3
+
4
+ // A one-time sign-in pass: a short-lived token a trusted issuer signs with its Ed25519 key, naming one person
5
+ // (`sub`), the application it is for (`aud`), one resource of that application (`resource`) and its own id (`jti`),
6
+ // which the application records as used. It is a compact JWS (RFC 7515) with the EdDSA algorithm (RFC 8037), so any
7
+ // JOSE library can issue one; the `typ` header keeps it from passing for another token the same key signs.
8
+ const PASS_TYPE = "pass+jwt";
9
+ const PASS_ALGORITHM = "EdDSA";
10
+ // How long signPass makes a pass last, and the longest lifetime verifyPass accepts.
11
+ const PASS_LIFETIME_SECONDS = 60;
12
+ const PASS_MAX_LIFETIME_SECONDS = 300;
13
+ // How far the issuer's clock may differ from the application's.
14
+ const PASS_CLOCK_SKEW_SECONDS = 30;
15
+ // Bounds on what a pass may hold, so a forged one costs little to refuse.
16
+ const PASS_MAX_LENGTH = 4096;
17
+ const PASS_MAX_TEXT_CLAIM_LENGTH = 255;
18
+
19
+ function base64urlJson(value) {
20
+ return Buffer.from(JSON.stringify(value)).toString("base64url");
21
+ }
22
+
23
+ function parseBase64urlJson(part) {
24
+ try {
25
+ const value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
26
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ function isClaimText(value) {
33
+ return typeof value === "string" && value.length > 0 && value.length <= PASS_MAX_TEXT_CLAIM_LENGTH;
34
+ }
35
+
36
+ function isClaimSeconds(value) {
37
+ return Number.isSafeInteger(value) && value > 0;
38
+ }
39
+
40
+ /**
41
+ * The issuer's Ed25519 public key from its text: a PEM block, or the base64 of its DER SubjectPublicKeyInfo (the PEM
42
+ * body on one line, which fits an environment variable).
43
+ * @param {string} text
44
+ */
45
+ function readPassPublicKey(text) {
46
+ const value = String(text || "").trim();
47
+ let key;
48
+ try {
49
+ key = value.startsWith("-----BEGIN")
50
+ ? createPublicKey(value)
51
+ : createPublicKey({ key: Buffer.from(value, "base64"), format: "der", type: "spki" });
52
+ } catch (error) {
53
+ throw new Error(`AUTH_PASS_PUBLIC_KEY is not a public key: ${error.message}`);
54
+ }
55
+ if (key.asymmetricKeyType !== "ed25519") {
56
+ throw new Error("AUTH_PASS_PUBLIC_KEY must be an Ed25519 public key.");
57
+ }
58
+ return key;
59
+ }
60
+
61
+ /**
62
+ * Pass sign-in's settings from the environment: AUTH_PASS_PUBLIC_KEY, the issuer's Ed25519 public key, turns it on,
63
+ * and then AUTH_PASS_AUDIENCE (the application the passes must name) and AUTH_PASS_RESOURCE (the one resource they
64
+ * must name, such as this server's machine) are required. Without the key it is off (null) and the application
65
+ * signs in only as before.
66
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
67
+ * @returns {Readonly<{ publicKey: import("node:crypto").KeyObject, audience: string, resource: string }> | null}
68
+ */
69
+ function resolvePassSignInFromEnv(env) {
70
+ const publicKeyText = String(env.AUTH_PASS_PUBLIC_KEY || "").trim();
71
+ if (!publicKeyText) {
72
+ return null;
73
+ }
74
+ const audience = String(env.AUTH_PASS_AUDIENCE || "").trim();
75
+ const resource = String(env.AUTH_PASS_RESOURCE || "").trim();
76
+ if (!audience || !resource) {
77
+ throw new Error("AUTH_PASS_AUDIENCE and AUTH_PASS_RESOURCE are required when AUTH_PASS_PUBLIC_KEY is set.");
78
+ }
79
+ return Object.freeze({
80
+ publicKey: readPassPublicKey(publicKeyText),
81
+ audience,
82
+ resource
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Signs a pass for one person, one application and one resource, valid for `lifetimeSeconds` from `now`, with a new
88
+ * random id unless one is given. For the issuer's server, which keeps the private key; the browser then POSTs the pass
89
+ * to the application's pass sign-in route.
90
+ * @param {object} input
91
+ * @param {import("node:crypto").KeyObject | string} input.privateKey The issuer's Ed25519 private key (a KeyObject or PEM).
92
+ * @param {string} input.subject Who the pass signs in, as the issuer names them; the application maps it to its account.
93
+ * @param {string} input.audience
94
+ * @param {string} input.resource
95
+ * @param {string} [input.id]
96
+ * @param {number} [input.lifetimeSeconds]
97
+ * @param {number} [input.now] Milliseconds since the epoch.
98
+ */
99
+ function signPass({
100
+ privateKey,
101
+ subject,
102
+ audience,
103
+ resource,
104
+ id = randomBytes(18).toString("base64url"),
105
+ lifetimeSeconds = PASS_LIFETIME_SECONDS,
106
+ now = Date.now()
107
+ }) {
108
+ if (!Number.isSafeInteger(lifetimeSeconds) || lifetimeSeconds < 1 || lifetimeSeconds > PASS_MAX_LIFETIME_SECONDS) {
109
+ throw new Error(`A pass lasts from 1 to ${PASS_MAX_LIFETIME_SECONDS} seconds.`);
110
+ }
111
+ for (const [name, value] of Object.entries({ subject, audience, resource, id })) {
112
+ if (!isClaimText(value)) {
113
+ throw new Error(`A pass's ${name} is text of 1 to ${PASS_MAX_TEXT_CLAIM_LENGTH} characters.`);
114
+ }
115
+ }
116
+ const issuedAt = Math.floor(now / 1000);
117
+ const body = `${base64urlJson({ alg: PASS_ALGORITHM, typ: PASS_TYPE })}.${base64urlJson({
118
+ jti: id,
119
+ sub: subject,
120
+ aud: audience,
121
+ resource,
122
+ iat: issuedAt,
123
+ exp: issuedAt + lifetimeSeconds
124
+ })}`;
125
+ return `${body}.${sign(null, Buffer.from(body), privateKey).toString("base64url")}`;
126
+ }
127
+
128
+ /**
129
+ * A verified pass: its id, who it signs in, what it is for, when it was issued and expires (seconds since the epoch),
130
+ * and the moment from which verifyPass refuses it as expired (`usableUntil`, ISO), until which the application must
131
+ * remember it was used.
132
+ * @typedef {Readonly<{
133
+ * id: string,
134
+ * subject: string,
135
+ * audience: string,
136
+ * resource: string,
137
+ * issuedAt: number,
138
+ * expiresAt: number,
139
+ * usableUntil: string
140
+ * }>} AuthPass
141
+ */
142
+
143
+ /**
144
+ * Checks a pass against the issuer's public key, the application's audience and resource, and the clock, and answers
145
+ * it; anything else is refused with a 401 naming the reason: `auth.pass.malformed` (not a pass, not yet valid, or
146
+ * longer-lived than five minutes), `auth.pass.badSignature`, `auth.pass.wrongAudience`, `auth.pass.wrongResource` or
147
+ * `auth.pass.expired`. Its claims are read only after its signature checks. Single use is the caller's: it records
148
+ * the pass's id until `usableUntil`.
149
+ * @param {unknown} token
150
+ * @param {object} settings What resolvePassSignInFromEnv answers.
151
+ * @param {import("node:crypto").KeyObject} settings.publicKey
152
+ * @param {string} settings.audience
153
+ * @param {string} settings.resource
154
+ * @param {number} [now] Milliseconds since the epoch.
155
+ * @returns {AuthPass}
156
+ */
157
+ function verifyPass(token, { publicKey, audience, resource }, now = Date.now()) {
158
+ const parts = typeof token === "string" && token.length <= PASS_MAX_LENGTH ? token.split(".") : [];
159
+ const header = parts.length === 3 ? parseBase64urlJson(parts[0]) : null;
160
+ if (header?.alg !== PASS_ALGORITHM || header.typ !== PASS_TYPE) {
161
+ throw createAuthError(AUTH_TEXTS.passMalformed);
162
+ }
163
+ if (!verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), publicKey, Buffer.from(parts[2], "base64url"))) {
164
+ throw createAuthError(AUTH_TEXTS.passBadSignature);
165
+ }
166
+ const claims = parseBase64urlJson(parts[1]);
167
+ if (!claims || ![claims.jti, claims.sub, claims.aud, claims.resource].every(isClaimText) ||
168
+ !isClaimSeconds(claims.iat) || !isClaimSeconds(claims.exp)) {
169
+ throw createAuthError(AUTH_TEXTS.passMalformed);
170
+ }
171
+ if (claims.aud !== audience) {
172
+ throw createAuthError(AUTH_TEXTS.passWrongAudience);
173
+ }
174
+ if (claims.resource !== resource) {
175
+ throw createAuthError(AUTH_TEXTS.passWrongResource);
176
+ }
177
+ const nowSeconds = Math.floor(now / 1000);
178
+ if (claims.exp + PASS_CLOCK_SKEW_SECONDS <= nowSeconds) {
179
+ throw createAuthError(AUTH_TEXTS.passExpired);
180
+ }
181
+ const lifetime = claims.exp - claims.iat;
182
+ if (claims.iat - PASS_CLOCK_SKEW_SECONDS > nowSeconds || lifetime < 1 || lifetime > PASS_MAX_LIFETIME_SECONDS) {
183
+ throw createAuthError(AUTH_TEXTS.passMalformed);
184
+ }
185
+ return Object.freeze({
186
+ id: claims.jti,
187
+ subject: claims.sub,
188
+ audience: claims.aud,
189
+ resource: claims.resource,
190
+ issuedAt: claims.iat,
191
+ expiresAt: claims.exp,
192
+ usableUntil: new Date((claims.exp + PASS_CLOCK_SKEW_SECONDS) * 1000).toISOString()
193
+ });
194
+ }
195
+
196
+ export { resolvePassSignInFromEnv, signPass, verifyPass };
@@ -165,6 +165,8 @@
165
165
  * whose staff lost their authenticator. `byUserId` names who reset it, for the audit event.
166
166
  * @property {(reply: object, result: object) => void} [writeOAuthStartCookies] Keeps the state of an OAuth sign-in that oauthStart() began.
167
167
  * @property {(reply: object) => void} [clearOAuthStartCookies]
168
+ * @property {(input: { pass: string }) => Promise<object>} [signInWithPass] Signs in the account a one-time signed pass
169
+ * names (`@jskit-ai/auth-core/server/passSignIn`), once per pass; local auth has it, with AUTH_PASS_PUBLIC_KEY set.
168
170
  * @property {(request: object, options?: { everywhere?: boolean }) => Promise<any>} [logoutEverywhere]
169
171
  * @property {() => object} [getSettingsProfileAuthInfo] What the account settings show about the provider's profile.
170
172
  * @property {() => object} [getOAuthProviderCatalog] The OAuth providers the sign-in screen offers.
@@ -5,6 +5,7 @@ const AUTH_PATHS = Object.freeze({
5
5
  LOGIN: "/api/login",
6
6
  LOGIN_OTP_REQUEST: "/api/login/otp/request",
7
7
  LOGIN_OTP_VERIFY: "/api/login/otp/verify",
8
+ LOGIN_PASS: "/api/login/pass",
8
9
  OAUTH_START_TEMPLATE: "/api/oauth/:provider/start",
9
10
  OAUTH_COMPLETE: "/api/oauth/complete",
10
11
  PASSWORD_FORGOT: "/api/password/forgot",
@@ -0,0 +1,122 @@
1
+ import assert from "node:assert/strict";
2
+ import { generateKeyPairSync, sign } from "node:crypto";
3
+ import test from "node:test";
4
+ import { resolvePassSignInFromEnv, signPass, verifyPass } from "../src/server/passSignIn.js";
5
+
6
+ const NOW = Date.parse("2026-11-13T10:00:00.000Z");
7
+ const issuer = generateKeyPairSync("ed25519");
8
+ const settings = Object.freeze({ publicKey: issuer.publicKey, audience: "editor", resource: "machine-7" });
9
+ const pass = (overrides = {}) =>
10
+ signPass({ privateKey: issuer.privateKey, subject: "ada", audience: "editor", resource: "machine-7", now: NOW, ...overrides });
11
+ const refused = (code, status = 401) => (error) => {
12
+ assert.equal(error.status, status);
13
+ assert.equal(error.code, code);
14
+ assert.ok(error.message.length > 0);
15
+ return true;
16
+ };
17
+
18
+ // A token with any header and claims, signed with the issuer's key, for the claims signPass never writes.
19
+ function signedToken(header, claims, privateKey = issuer.privateKey) {
20
+ const body = [header, claims].map((part) => Buffer.from(JSON.stringify(part)).toString("base64url")).join(".");
21
+ return `${body}.${sign(null, Buffer.from(body), privateKey).toString("base64url")}`;
22
+ }
23
+
24
+ test("a pass the issuer signed for this audience and resource is accepted, with what it names", () => {
25
+ const verified = verifyPass(pass({ id: "pass-1" }), settings, NOW + 59_000);
26
+ assert.deepEqual(verified, {
27
+ id: "pass-1",
28
+ subject: "ada",
29
+ audience: "editor",
30
+ resource: "machine-7",
31
+ issuedAt: NOW / 1000,
32
+ expiresAt: NOW / 1000 + 60,
33
+ usableUntil: "2026-11-13T10:01:30.000Z"
34
+ });
35
+ assert.equal(Object.isFrozen(verified), true);
36
+ // A new id for every pass signed without one.
37
+ assert.notEqual(verifyPass(pass(), settings, NOW).id, verifyPass(pass(), settings, NOW).id);
38
+ });
39
+
40
+ test("an expired pass is refused, after the clock skew", () => {
41
+ const token = pass({ lifetimeSeconds: 60 });
42
+ assert.equal(verifyPass(token, settings, NOW + 89_999).subject, "ada");
43
+ assert.throws(() => verifyPass(token, settings, NOW + 90_000), refused("auth.pass.expired"));
44
+ });
45
+
46
+ test("a pass another key signed, or one changed after signing, is refused as wrongly signed", () => {
47
+ const stranger = generateKeyPairSync("ed25519");
48
+ assert.throws(() => verifyPass(pass({ privateKey: stranger.privateKey }), settings, NOW), refused("auth.pass.badSignature"));
49
+
50
+ const [header, , signature] = pass().split(".");
51
+ const changed = Buffer.from(JSON.stringify({
52
+ jti: "pass-2", sub: "admin", aud: "editor", resource: "machine-7", iat: NOW / 1000, exp: NOW / 1000 + 60
53
+ })).toString("base64url");
54
+ assert.throws(() => verifyPass(`${header}.${changed}.${signature}`, settings, NOW), refused("auth.pass.badSignature"));
55
+ });
56
+
57
+ test("a pass for another application is refused as for another audience", () => {
58
+ assert.throws(() => verifyPass(pass({ audience: "console" }), settings, NOW), refused("auth.pass.wrongAudience"));
59
+ });
60
+
61
+ test("a pass for another resource is refused as for another resource", () => {
62
+ assert.throws(() => verifyPass(pass({ resource: "machine-8" }), settings, NOW), refused("auth.pass.wrongResource"));
63
+ });
64
+
65
+ test("anything that is not a pass is refused as malformed, its claims read only once its signature checks", () => {
66
+ const claims = { jti: "pass-3", sub: "ada", aud: "editor", resource: "machine-7", iat: NOW / 1000, exp: NOW / 1000 + 60 };
67
+ const header = { alg: "EdDSA", typ: "pass+jwt" };
68
+ for (const token of [
69
+ undefined,
70
+ "",
71
+ "not.a.pass",
72
+ "a.b",
73
+ `${pass()}.extra`,
74
+ "x".repeat(4097),
75
+ // Another algorithm or another kind of token the same key signs.
76
+ signedToken({ alg: "none", typ: "pass+jwt" }, claims),
77
+ signedToken({ alg: "EdDSA", typ: "JWT" }, claims),
78
+ // Claims missing, of the wrong type, or too long.
79
+ signedToken(header, { ...claims, sub: undefined }),
80
+ signedToken(header, { ...claims, jti: 7 }),
81
+ signedToken(header, { ...claims, resource: "r".repeat(256) }),
82
+ signedToken(header, { ...claims, exp: String(claims.exp) }),
83
+ signedToken(header, [claims]),
84
+ // Not yet valid, longer-lived than five minutes, or expiring before it was issued.
85
+ signedToken(header, { ...claims, iat: claims.iat + 31, exp: claims.exp + 31 }),
86
+ signedToken(header, { ...claims, exp: claims.iat + 301 }),
87
+ signedToken(header, { ...claims, exp: claims.iat })
88
+ ]) {
89
+ assert.throws(() => verifyPass(token, settings, NOW), refused("auth.pass.malformed"), String(token).slice(0, 40));
90
+ }
91
+ // Within the clock skew, a pass issued a little in the future is accepted.
92
+ assert.equal(verifyPass(signedToken(header, { ...claims, iat: claims.iat + 30, exp: claims.exp + 30 }), settings, NOW).id, "pass-3");
93
+ });
94
+
95
+ test("signPass refuses what verifyPass would", () => {
96
+ assert.throws(() => pass({ lifetimeSeconds: 301 }), /from 1 to 300 seconds/u);
97
+ assert.throws(() => pass({ lifetimeSeconds: 0 }), /from 1 to 300 seconds/u);
98
+ assert.throws(() => pass({ subject: "" }), /subject is text of 1 to 255 characters/u);
99
+ assert.throws(() => pass({ resource: "r".repeat(256) }), /resource is text/u);
100
+ });
101
+
102
+ test("pass sign-in is off without AUTH_PASS_PUBLIC_KEY, and its settings are checked when it is on", () => {
103
+ assert.equal(resolvePassSignInFromEnv({}), null);
104
+ assert.equal(resolvePassSignInFromEnv({ AUTH_PASS_PUBLIC_KEY: " ", AUTH_PASS_AUDIENCE: "editor" }), null);
105
+
106
+ const pem = issuer.publicKey.export({ type: "spki", format: "pem" });
107
+ const oneLine = issuer.publicKey.export({ type: "spki", format: "der" }).toString("base64");
108
+ for (const key of [pem, oneLine]) {
109
+ const resolved = resolvePassSignInFromEnv({ AUTH_PASS_PUBLIC_KEY: key, AUTH_PASS_AUDIENCE: " editor ", AUTH_PASS_RESOURCE: "machine-7" });
110
+ assert.equal(resolved.audience, "editor");
111
+ assert.equal(resolved.resource, "machine-7");
112
+ assert.equal(verifyPass(pass(), resolved, NOW).subject, "ada");
113
+ }
114
+
115
+ assert.throws(() => resolvePassSignInFromEnv({ AUTH_PASS_PUBLIC_KEY: oneLine, AUTH_PASS_AUDIENCE: "editor" }),
116
+ /AUTH_PASS_AUDIENCE and AUTH_PASS_RESOURCE are required/u);
117
+ assert.throws(() => resolvePassSignInFromEnv({ AUTH_PASS_PUBLIC_KEY: "not a key", AUTH_PASS_AUDIENCE: "a", AUTH_PASS_RESOURCE: "r" }),
118
+ /AUTH_PASS_PUBLIC_KEY is not a public key/u);
119
+ const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 }).publicKey.export({ type: "spki", format: "pem" });
120
+ assert.throws(() => resolvePassSignInFromEnv({ AUTH_PASS_PUBLIC_KEY: rsa, AUTH_PASS_AUDIENCE: "a", AUTH_PASS_RESOURCE: "r" }),
121
+ /must be an Ed25519 public key/u);
122
+ });