@weft-framework/server 0.0.0-stage → 0.0.3
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/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/account.d.ts +124 -0
- package/dist/account.js +344 -0
- package/dist/action.d.ts +43 -0
- package/dist/action.js +135 -0
- package/dist/admin.d.ts +99 -0
- package/dist/admin.js +431 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +72 -0
- package/dist/app.d.ts +202 -0
- package/dist/app.js +3692 -0
- package/dist/assets.d.ts +4 -0
- package/dist/assets.js +91 -0
- package/dist/auth.d.ts +150 -0
- package/dist/auth.js +215 -0
- package/dist/backup.d.ts +46 -0
- package/dist/backup.js +345 -0
- package/dist/build.d.ts +33 -0
- package/dist/build.js +274 -0
- package/dist/bun.d.ts +30 -0
- package/dist/bun.js +53 -0
- package/dist/calendar.d.ts +161 -0
- package/dist/calendar.js +690 -0
- package/dist/compiler.d.ts +13 -0
- package/dist/compiler.js +58 -0
- package/dist/compress.d.ts +6 -0
- package/dist/compress.js +78 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +317 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.js +1 -0
- package/dist/contract.d.ts +18 -0
- package/dist/contract.js +171 -0
- package/dist/datamap.d.ts +24 -0
- package/dist/datamap.js +365 -0
- package/dist/db-backup.d.ts +27 -0
- package/dist/db-backup.js +115 -0
- package/dist/dev-events.d.ts +14 -0
- package/dist/dev-events.js +135 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +240 -0
- package/dist/devtools-client.d.ts +1 -0
- package/dist/devtools-client.js +362 -0
- package/dist/devtools.d.ts +87 -0
- package/dist/devtools.js +68 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +7 -0
- package/dist/email-signin.d.ts +92 -0
- package/dist/email-signin.js +259 -0
- package/dist/env.d.ts +1 -0
- package/dist/env.js +15 -0
- package/dist/explain.d.ts +12 -0
- package/dist/explain.js +217 -0
- package/dist/files.d.ts +6 -0
- package/dist/files.js +170 -0
- package/dist/grants.d.ts +69 -0
- package/dist/grants.js +206 -0
- package/dist/image/bitmap.d.ts +11 -0
- package/dist/image/bitmap.js +172 -0
- package/dist/image/jpeg.d.ts +10 -0
- package/dist/image/jpeg.js +697 -0
- package/dist/image/png.d.ts +8 -0
- package/dist/image/png.js +282 -0
- package/dist/image/transform.d.ts +20 -0
- package/dist/image/transform.js +52 -0
- package/dist/image/worker.d.ts +1 -0
- package/dist/image/worker.js +11 -0
- package/dist/images.d.ts +39 -0
- package/dist/images.js +283 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +31 -0
- package/dist/inspect-hub.d.ts +42 -0
- package/dist/inspect-hub.js +14 -0
- package/dist/inspector.d.ts +51 -0
- package/dist/inspector.js +193 -0
- package/dist/job-admin.d.ts +55 -0
- package/dist/job-admin.js +89 -0
- package/dist/jobs.d.ts +222 -0
- package/dist/jobs.js +789 -0
- package/dist/live.d.ts +72 -0
- package/dist/live.js +481 -0
- package/dist/load-config.d.ts +2 -0
- package/dist/load-config.js +41 -0
- package/dist/log.d.ts +20 -0
- package/dist/log.js +143 -0
- package/dist/mail.d.ts +189 -0
- package/dist/mail.js +999 -0
- package/dist/media.d.ts +129 -0
- package/dist/media.js +470 -0
- package/dist/meta.d.ts +54 -0
- package/dist/meta.js +146 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +101 -0
- package/dist/migrate.d.ts +12 -0
- package/dist/migrate.js +88 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +96 -0
- package/dist/notice.d.ts +21 -0
- package/dist/notice.js +48 -0
- package/dist/npm.d.ts +16 -0
- package/dist/npm.js +347 -0
- package/dist/oauth.d.ts +76 -0
- package/dist/oauth.js +408 -0
- package/dist/otel.d.ts +57 -0
- package/dist/otel.js +293 -0
- package/dist/passkey.d.ts +99 -0
- package/dist/passkey.js +572 -0
- package/dist/password.d.ts +8 -0
- package/dist/password.js +65 -0
- package/dist/pdf.d.ts +46 -0
- package/dist/pdf.js +332 -0
- package/dist/personal-data.d.ts +22 -0
- package/dist/personal-data.js +148 -0
- package/dist/pointers.d.ts +9 -0
- package/dist/pointers.js +148 -0
- package/dist/postcss.d.ts +3 -0
- package/dist/postcss.js +89 -0
- package/dist/presence.d.ts +27 -0
- package/dist/presence.js +161 -0
- package/dist/preview.d.ts +25 -0
- package/dist/preview.js +353 -0
- package/dist/production.d.ts +16 -0
- package/dist/production.js +119 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.js +536 -0
- package/dist/regions.d.ts +47 -0
- package/dist/regions.js +511 -0
- package/dist/replay.d.ts +44 -0
- package/dist/replay.js +259 -0
- package/dist/router.d.ts +29 -0
- package/dist/router.js +146 -0
- package/dist/rules-diff.d.ts +18 -0
- package/dist/rules-diff.js +165 -0
- package/dist/rules-test.d.ts +17 -0
- package/dist/rules-test.js +108 -0
- package/dist/saml.d.ts +160 -0
- package/dist/saml.js +959 -0
- package/dist/seal.d.ts +35 -0
- package/dist/seal.js +107 -0
- package/dist/secret.d.ts +14 -0
- package/dist/secret.js +110 -0
- package/dist/security.d.ts +53 -0
- package/dist/security.js +250 -0
- package/dist/seed.d.ts +16 -0
- package/dist/seed.js +94 -0
- package/dist/seo.d.ts +42 -0
- package/dist/seo.js +175 -0
- package/dist/settings.d.ts +79 -0
- package/dist/settings.js +212 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.js +283 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +118 -0
- package/dist/storage.d.ts +13 -0
- package/dist/storage.js +55 -0
- package/dist/support.d.ts +83 -0
- package/dist/support.js +236 -0
- package/dist/sync.d.ts +35 -0
- package/dist/sync.js +167 -0
- package/dist/tailwind.d.ts +14 -0
- package/dist/tailwind.js +117 -0
- package/dist/two-factor.d.ts +103 -0
- package/dist/two-factor.js +435 -0
- package/dist/uploads.d.ts +185 -0
- package/dist/uploads.js +991 -0
- package/dist/webhooks.d.ts +169 -0
- package/dist/webhooks.js +758 -0
- package/dist/webpush.d.ts +97 -0
- package/dist/webpush.js +372 -0
- package/dist/wizard.d.ts +141 -0
- package/dist/wizard.js +410 -0
- package/dist/workflows.d.ts +134 -0
- package/dist/workflows.js +511 -0
- package/package.json +186 -4
package/dist/saml.js
ADDED
|
@@ -0,0 +1,959 @@
|
|
|
1
|
+
import { X509Certificate, constants, createDecipheriv, createPrivateKey, createPublicKey, privateDecrypt, randomBytes, sign as rsaSign, verify as rsaVerify, } from "node:crypto";
|
|
2
|
+
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
|
3
|
+
import { DOMParser } from "@xmldom/xmldom";
|
|
4
|
+
import { SignedXml } from "xml-crypto";
|
|
5
|
+
import { SignInError, checkEndpoint } from "./oauth.js";
|
|
6
|
+
import { isSecret } from "./secret.js";
|
|
7
|
+
const NS = {
|
|
8
|
+
proto: "urn:oasis:names:tc:SAML:2.0:protocol",
|
|
9
|
+
saml: "urn:oasis:names:tc:SAML:2.0:assertion",
|
|
10
|
+
ds: "http://www.w3.org/2000/09/xmldsig#",
|
|
11
|
+
md: "urn:oasis:names:tc:SAML:2.0:metadata",
|
|
12
|
+
xenc: "http://www.w3.org/2001/04/xmlenc#",
|
|
13
|
+
xenc11: "http://www.w3.org/2009/xmlenc11#",
|
|
14
|
+
};
|
|
15
|
+
const BEARER = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
|
|
16
|
+
const POST_BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
|
|
17
|
+
const REDIRECT_BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
|
|
18
|
+
const SUCCESS = "urn:oasis:names:tc:SAML:2.0:status:Success";
|
|
19
|
+
const DENIED = new Set(["urn:oasis:names:tc:SAML:2.0:status:AuthnFailed", "urn:oasis:names:tc:SAML:2.0:status:RequestDenied"]);
|
|
20
|
+
const TRANSIENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient";
|
|
21
|
+
const EMAIL_FORMAT = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
|
|
22
|
+
const UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";
|
|
23
|
+
const RSA_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
|
|
24
|
+
const RSA_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
|
|
25
|
+
const RSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
|
|
26
|
+
const HASH_ALGS = ["http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmlenc#sha512"];
|
|
27
|
+
const HASH_SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1";
|
|
28
|
+
const C14N_ALGS = [
|
|
29
|
+
"http://www.w3.org/2001/10/xml-exc-c14n#",
|
|
30
|
+
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
|
|
31
|
+
"http://www.w3.org/2000/09/xmldsig#enveloped-signature",
|
|
32
|
+
];
|
|
33
|
+
const REDIRECT_SIG = { [RSA_SHA256]: "sha256", [RSA_SHA512]: "sha512" };
|
|
34
|
+
const BLOCK = {
|
|
35
|
+
[`${NS.xenc}aes128-cbc`]: ["aes-128-cbc", 16, "cbc"],
|
|
36
|
+
[`${NS.xenc}aes192-cbc`]: ["aes-192-cbc", 24, "cbc"],
|
|
37
|
+
[`${NS.xenc}aes256-cbc`]: ["aes-256-cbc", 32, "cbc"],
|
|
38
|
+
[`${NS.xenc11}aes128-gcm`]: ["aes-128-gcm", 16, "gcm"],
|
|
39
|
+
[`${NS.xenc11}aes192-gcm`]: ["aes-192-gcm", 24, "gcm"],
|
|
40
|
+
[`${NS.xenc11}aes256-gcm`]: ["aes-256-gcm", 32, "gcm"],
|
|
41
|
+
};
|
|
42
|
+
const OAEP_DIGEST = {
|
|
43
|
+
[HASH_SHA1]: "sha1",
|
|
44
|
+
[`${NS.xenc}sha256`]: "sha256",
|
|
45
|
+
[`${NS.xenc}sha512`]: "sha512",
|
|
46
|
+
};
|
|
47
|
+
const OAEP_MGF = {
|
|
48
|
+
[`${NS.xenc11}mgf1sha1`]: "sha1",
|
|
49
|
+
[`${NS.xenc11}mgf1sha256`]: "sha256",
|
|
50
|
+
[`${NS.xenc11}mgf1sha512`]: "sha512",
|
|
51
|
+
};
|
|
52
|
+
const DEFAULT_EMAIL = [
|
|
53
|
+
"email",
|
|
54
|
+
"mail",
|
|
55
|
+
"emailAddress",
|
|
56
|
+
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
|
|
57
|
+
"urn:oid:0.9.2342.19200300.100.1.3",
|
|
58
|
+
];
|
|
59
|
+
const DEFAULT_NAME = [
|
|
60
|
+
"displayName",
|
|
61
|
+
"name",
|
|
62
|
+
"http://schemas.microsoft.com/identity/claims/displayname",
|
|
63
|
+
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
|
|
64
|
+
"urn:oid:2.16.840.1.113730.3.1.241",
|
|
65
|
+
];
|
|
66
|
+
export const SAML_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
67
|
+
const PATH = "/_weft/auth/saml/";
|
|
68
|
+
const DAY = 86_400_000;
|
|
69
|
+
export const MAX_SAML_RESPONSE = 512 * 1024;
|
|
70
|
+
const MAX_VALUE = 2048;
|
|
71
|
+
const MAX_ATTRIBUTES = 100;
|
|
72
|
+
const MAX_VALUES = 50;
|
|
73
|
+
const DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
|
|
74
|
+
const EMAIL = /^[^\s@<>"]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
|
|
75
|
+
const B64 = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
76
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
77
|
+
function fail(message) {
|
|
78
|
+
throw new SignInError("failed", `saml: ${message}`);
|
|
79
|
+
}
|
|
80
|
+
function escapeXml(s) {
|
|
81
|
+
return s.replace(/[<>&"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
82
|
+
}
|
|
83
|
+
function base64(raw, what) {
|
|
84
|
+
const b = raw.replace(/\s+/g, "");
|
|
85
|
+
if (b === "" || !B64.test(b))
|
|
86
|
+
fail(`${what} is not base64`);
|
|
87
|
+
return Buffer.from(b, "base64");
|
|
88
|
+
}
|
|
89
|
+
function instant(ms) {
|
|
90
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
91
|
+
}
|
|
92
|
+
function parseXml(xml, what) {
|
|
93
|
+
if (/<!DOCTYPE|<!ENTITY/i.test(xml))
|
|
94
|
+
fail(`${what} has a document type declaration`);
|
|
95
|
+
let doc;
|
|
96
|
+
try {
|
|
97
|
+
const parser = new DOMParser({
|
|
98
|
+
errorHandler: {
|
|
99
|
+
warning: () => { },
|
|
100
|
+
error: (m) => {
|
|
101
|
+
throw new Error(m);
|
|
102
|
+
},
|
|
103
|
+
fatalError: (m) => {
|
|
104
|
+
throw new Error(m);
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
doc = parser.parseFromString(xml, "text/xml");
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
fail(`${what} is not well-formed XML`);
|
|
112
|
+
}
|
|
113
|
+
const root = doc?.documentElement;
|
|
114
|
+
if (!root)
|
|
115
|
+
fail(`${what} is not well-formed XML`);
|
|
116
|
+
return root;
|
|
117
|
+
}
|
|
118
|
+
function elementChildren(el) {
|
|
119
|
+
const out = [];
|
|
120
|
+
for (let n = el.firstChild; n; n = n.nextSibling)
|
|
121
|
+
if (n.nodeType === 1)
|
|
122
|
+
out.push(n);
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
const is = (el, ns, name) => el.namespaceURI === ns && el.localName === name;
|
|
126
|
+
function kids(el, ns, name) {
|
|
127
|
+
return elementChildren(el).filter((c) => is(c, ns, name));
|
|
128
|
+
}
|
|
129
|
+
function kid(el, ns, name) {
|
|
130
|
+
const k = kids(el, ns, name);
|
|
131
|
+
if (k.length > 1)
|
|
132
|
+
fail(`more than one <${name}> in <${el.localName}>`);
|
|
133
|
+
return k[0] ?? null;
|
|
134
|
+
}
|
|
135
|
+
function descendants(root, ns, name) {
|
|
136
|
+
const out = [];
|
|
137
|
+
const stack = [root];
|
|
138
|
+
while (stack.length > 0) {
|
|
139
|
+
const el = stack.pop();
|
|
140
|
+
if (is(el, ns, name))
|
|
141
|
+
out.push(el);
|
|
142
|
+
stack.push(...elementChildren(el));
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
function text(el, max = MAX_VALUE) {
|
|
147
|
+
let s = "";
|
|
148
|
+
for (let n = el.firstChild; n; n = n.nextSibling) {
|
|
149
|
+
if (n.nodeType !== 3 && n.nodeType !== 4)
|
|
150
|
+
fail(`unexpected content in <${el.localName}>`);
|
|
151
|
+
s += n.nodeValue ?? "";
|
|
152
|
+
}
|
|
153
|
+
s = s.trim();
|
|
154
|
+
if (s.length > max)
|
|
155
|
+
fail(`<${el.localName}> is too long`);
|
|
156
|
+
return s;
|
|
157
|
+
}
|
|
158
|
+
function attr(el, name) {
|
|
159
|
+
return el.hasAttribute(name) ? el.getAttribute(name) : null;
|
|
160
|
+
}
|
|
161
|
+
function time(raw, what) {
|
|
162
|
+
if (raw === null)
|
|
163
|
+
return null;
|
|
164
|
+
const t = DATE.test(raw) ? Date.parse(raw) : NaN;
|
|
165
|
+
if (!Number.isFinite(t))
|
|
166
|
+
fail(`${what} is not a date`);
|
|
167
|
+
return t;
|
|
168
|
+
}
|
|
169
|
+
function namespacesAt(el) {
|
|
170
|
+
const seen = new Map();
|
|
171
|
+
for (let n = el; n && n.nodeType === 1; n = n.parentNode) {
|
|
172
|
+
const attrs = n.attributes;
|
|
173
|
+
for (let i = 0; i < attrs.length; i++) {
|
|
174
|
+
const a = attrs.item(i);
|
|
175
|
+
if ((a.name === "xmlns" || a.name.startsWith("xmlns:")) && !seen.has(a.name))
|
|
176
|
+
seen.set(a.name, a.value);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return [...seen].map(([k, v]) => ` ${k}="${escapeXml(v)}"`).join("");
|
|
180
|
+
}
|
|
181
|
+
function readCert(raw) {
|
|
182
|
+
if (typeof raw !== "string")
|
|
183
|
+
throw new TypeError("saml: a certificate must be a string");
|
|
184
|
+
const body = raw.replace(/-----BEGIN CERTIFICATE-----|-----END CERTIFICATE-----/g, "").replace(/\s+/g, "");
|
|
185
|
+
if (!B64.test(body))
|
|
186
|
+
throw new TypeError("saml: a certificate is not PEM or base64");
|
|
187
|
+
const pem = `-----BEGIN CERTIFICATE-----\n${body.replace(/.{1,64}/g, "$&\n")}-----END CERTIFICATE-----\n`;
|
|
188
|
+
let cert;
|
|
189
|
+
try {
|
|
190
|
+
cert = new X509Certificate(pem);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
throw new TypeError("saml: a certificate is not PEM or base64 of an X.509 certificate");
|
|
194
|
+
}
|
|
195
|
+
if (cert.publicKey.asymmetricKeyType !== "rsa")
|
|
196
|
+
throw new TypeError("saml: only RSA certificates are supported");
|
|
197
|
+
return {
|
|
198
|
+
pem,
|
|
199
|
+
subject: cert.subject,
|
|
200
|
+
notBefore: Date.parse(cert.validFrom),
|
|
201
|
+
notAfter: Date.parse(cert.validTo),
|
|
202
|
+
fingerprint256: cert.fingerprint256,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
function readSpKey(k) {
|
|
206
|
+
const pem = isSecret(k?.privateKey) ? k.privateKey.reveal() : k?.privateKey;
|
|
207
|
+
if (typeof pem !== "string")
|
|
208
|
+
throw new TypeError("defineSaml: sp.keys[].privateKey must be PEM");
|
|
209
|
+
let key;
|
|
210
|
+
try {
|
|
211
|
+
key = createPrivateKey(pem);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
throw new TypeError("defineSaml: an sp private key is not a PEM private key");
|
|
215
|
+
}
|
|
216
|
+
if (key.asymmetricKeyType !== "rsa")
|
|
217
|
+
throw new TypeError("defineSaml: sp keys must be RSA");
|
|
218
|
+
const cert = readCert(k.certificate);
|
|
219
|
+
const mine = createPublicKey(key).export({ type: "spki", format: "der" });
|
|
220
|
+
const theirs = new X509Certificate(cert.pem).publicKey.export({ type: "spki", format: "der" });
|
|
221
|
+
if (!mine.equals(theirs))
|
|
222
|
+
throw new TypeError("defineSaml: an sp certificate does not match its private key");
|
|
223
|
+
return { key, cert };
|
|
224
|
+
}
|
|
225
|
+
export function checkSamlConnection(c) {
|
|
226
|
+
if (typeof c?.id !== "string" || !SAML_ID.test(c.id) || c.id === "logout") {
|
|
227
|
+
throw new TypeError("saml: a connection id is 1-64 lowercase letters, digits or - (not `logout`)");
|
|
228
|
+
}
|
|
229
|
+
if (typeof c.idpEntityId !== "string" || c.idpEntityId === "" || c.idpEntityId.length > 1024) {
|
|
230
|
+
throw new TypeError(`saml: connection ${c.id} has no idpEntityId`);
|
|
231
|
+
}
|
|
232
|
+
const ssoUrl = checkEndpoint(c.ssoUrl, `connection ${c.id} ssoUrl`);
|
|
233
|
+
const sloUrl = c.sloUrl ? checkEndpoint(c.sloUrl, `connection ${c.id} sloUrl`) : null;
|
|
234
|
+
const sloResponseUrl = c.sloResponseUrl ? checkEndpoint(c.sloResponseUrl, `connection ${c.id} sloResponseUrl`) : null;
|
|
235
|
+
if (!Array.isArray(c.certificates) || c.certificates.length === 0 || c.certificates.length > 4) {
|
|
236
|
+
throw new TypeError(`saml: connection ${c.id} needs 1-4 certificates`);
|
|
237
|
+
}
|
|
238
|
+
const domains = (c.emailDomains ?? []).map((d) => {
|
|
239
|
+
if (typeof d !== "string" || !/^[a-z0-9.-]{1,253}$/i.test(d))
|
|
240
|
+
throw new TypeError(`saml: connection ${c.id} has a bad email domain`);
|
|
241
|
+
return d.toLowerCase();
|
|
242
|
+
});
|
|
243
|
+
return { ...c, ssoUrl, sloUrl, sloResponseUrl, certificates: c.certificates.map(readCert), emailDomains: domains };
|
|
244
|
+
}
|
|
245
|
+
function usableCerts(c, now) {
|
|
246
|
+
if (c.ignoreCertificateExpiry)
|
|
247
|
+
return c.certificates;
|
|
248
|
+
const ok = c.certificates.filter((x) => x.notBefore <= now && now < x.notAfter);
|
|
249
|
+
if (ok.length === 0)
|
|
250
|
+
fail(`connection ${c.id}: its certificates have expired or are not valid yet`);
|
|
251
|
+
return ok;
|
|
252
|
+
}
|
|
253
|
+
function only(map, keys) {
|
|
254
|
+
const out = {};
|
|
255
|
+
for (const k of keys)
|
|
256
|
+
if (k in map)
|
|
257
|
+
out[k] = map[k];
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
function verifiedCopy(xml, sig, c, now) {
|
|
261
|
+
const host = sig.parentNode;
|
|
262
|
+
const sigAlgs = c.allowSha1 ? [RSA_SHA256, RSA_SHA512, RSA_SHA1] : [RSA_SHA256, RSA_SHA512];
|
|
263
|
+
for (const cert of usableCerts(c, now)) {
|
|
264
|
+
const v = new SignedXml({ publicCert: cert.pem, getCertFromKeyInfo: () => null });
|
|
265
|
+
v.SignatureAlgorithms = only(v.SignatureAlgorithms, sigAlgs);
|
|
266
|
+
v.HashAlgorithms = only(v.HashAlgorithms, c.allowSha1 ? [...HASH_ALGS, HASH_SHA1] : HASH_ALGS);
|
|
267
|
+
v.CanonicalizationAlgorithms = only(v.CanonicalizationAlgorithms, C14N_ALGS);
|
|
268
|
+
let ok = false;
|
|
269
|
+
try {
|
|
270
|
+
v.loadSignature(sig);
|
|
271
|
+
ok = v.checkSignature(xml) === true;
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
ok = false;
|
|
275
|
+
}
|
|
276
|
+
if (!ok)
|
|
277
|
+
continue;
|
|
278
|
+
const refs = v.getSignedReferences();
|
|
279
|
+
if (refs.length !== 1)
|
|
280
|
+
fail("a signature must cover exactly one element");
|
|
281
|
+
const copy = parseXml(refs[0], "the signed element");
|
|
282
|
+
if (copy.namespaceURI !== host.namespaceURI || copy.localName !== host.localName || attr(copy, "ID") !== attr(host, "ID")) {
|
|
283
|
+
fail("the signature covers another element");
|
|
284
|
+
}
|
|
285
|
+
return copy;
|
|
286
|
+
}
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
function redirectUrl(target, param, xml, relay, key) {
|
|
290
|
+
let q = `${param}=${encodeURIComponent(deflateRawSync(Buffer.from(xml, "utf8")).toString("base64"))}`;
|
|
291
|
+
if (relay !== null)
|
|
292
|
+
q += `&RelayState=${encodeURIComponent(relay)}`;
|
|
293
|
+
if (key) {
|
|
294
|
+
q += `&SigAlg=${encodeURIComponent(RSA_SHA256)}`;
|
|
295
|
+
q += `&Signature=${encodeURIComponent(rsaSign("sha256", Buffer.from(q, "utf8"), key).toString("base64"))}`;
|
|
296
|
+
}
|
|
297
|
+
return `${target}${target.includes("?") ? "&" : "?"}${q}`;
|
|
298
|
+
}
|
|
299
|
+
const formDecode = (v) => {
|
|
300
|
+
try {
|
|
301
|
+
return decodeURIComponent(v.replace(/\+/g, " "));
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return fail("a query value is not URL-encoded");
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
function readRedirect(search, c, now) {
|
|
308
|
+
const raw = new Map();
|
|
309
|
+
for (const part of search.replace(/^\?/, "").split("&")) {
|
|
310
|
+
if (part === "")
|
|
311
|
+
continue;
|
|
312
|
+
const eq = part.indexOf("=");
|
|
313
|
+
const name = eq < 0 ? part : part.slice(0, eq);
|
|
314
|
+
if (raw.has(name))
|
|
315
|
+
fail(`${name} is given twice`);
|
|
316
|
+
raw.set(name, eq < 0 ? "" : part.slice(eq + 1));
|
|
317
|
+
}
|
|
318
|
+
const param = raw.has("SAMLRequest") ? "SAMLRequest" : raw.has("SAMLResponse") ? "SAMLResponse" : null;
|
|
319
|
+
if (param === null || (raw.has("SAMLRequest") && raw.has("SAMLResponse")))
|
|
320
|
+
fail("no SAML message");
|
|
321
|
+
const sigAlg = raw.get("SigAlg");
|
|
322
|
+
const signature = raw.get("Signature");
|
|
323
|
+
if (sigAlg === undefined || signature === undefined)
|
|
324
|
+
fail("the message is not signed");
|
|
325
|
+
const hash = REDIRECT_SIG[formDecode(sigAlg)] ?? (c.allowSha1 && formDecode(sigAlg) === RSA_SHA1 ? "sha1" : undefined);
|
|
326
|
+
if (!hash)
|
|
327
|
+
fail("the message's signature algorithm is not accepted");
|
|
328
|
+
let signed = `${param}=${raw.get(param)}`;
|
|
329
|
+
if (raw.has("RelayState"))
|
|
330
|
+
signed += `&RelayState=${raw.get("RelayState")}`;
|
|
331
|
+
signed += `&SigAlg=${sigAlg}`;
|
|
332
|
+
const sig = base64(formDecode(signature), "the signature");
|
|
333
|
+
if (!usableCerts(c, now).some((cert) => rsaVerify(hash, Buffer.from(signed, "utf8"), cert.pem, sig))) {
|
|
334
|
+
fail("the message's signature does not verify");
|
|
335
|
+
}
|
|
336
|
+
const packed = base64(formDecode(raw.get(param)), "the message");
|
|
337
|
+
let xml;
|
|
338
|
+
try {
|
|
339
|
+
xml = utf8.decode(inflateRawSync(packed, { maxOutputLength: 1 << 20 }));
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
fail("the message cannot be inflated");
|
|
343
|
+
}
|
|
344
|
+
return { param, xml, relay: raw.has("RelayState") ? formDecode(raw.get("RelayState")) : null };
|
|
345
|
+
}
|
|
346
|
+
function decrypt(holder, keys, cbcAllowed) {
|
|
347
|
+
const unable = () => fail("the encrypted part cannot be decrypted");
|
|
348
|
+
if (keys.length === 0)
|
|
349
|
+
fail("the IdP encrypts, and the app has no sp keys");
|
|
350
|
+
const data = kids(holder, NS.xenc, "EncryptedData");
|
|
351
|
+
if (data.length !== 1)
|
|
352
|
+
fail("expected one EncryptedData");
|
|
353
|
+
const d = data[0];
|
|
354
|
+
const type = attr(d, "Type");
|
|
355
|
+
if (type !== null && type !== `${NS.xenc}Element`)
|
|
356
|
+
fail("only encrypted elements are supported");
|
|
357
|
+
const method = kid(d, NS.xenc, "EncryptionMethod");
|
|
358
|
+
const block = method ? BLOCK[attr(method, "Algorithm") ?? ""] : undefined;
|
|
359
|
+
if (!block)
|
|
360
|
+
fail("the content encryption algorithm is not accepted");
|
|
361
|
+
const [cipherName, keyLength, mode] = block;
|
|
362
|
+
if (mode === "cbc" && !cbcAllowed) {
|
|
363
|
+
fail("AES-CBC is accepted only when the whole response is signed; have the IdP sign the response or use AES-GCM");
|
|
364
|
+
}
|
|
365
|
+
const keyInfo = kid(d, NS.ds, "KeyInfo");
|
|
366
|
+
const wrapped = [...(keyInfo ? kids(keyInfo, NS.xenc, "EncryptedKey") : []), ...kids(holder, NS.xenc, "EncryptedKey")];
|
|
367
|
+
if (wrapped.length === 0 || wrapped.length > 8)
|
|
368
|
+
fail("expected an EncryptedKey");
|
|
369
|
+
let cek = null;
|
|
370
|
+
outer: for (const ek of wrapped) {
|
|
371
|
+
const m = kid(ek, NS.xenc, "EncryptionMethod");
|
|
372
|
+
const alg = m ? attr(m, "Algorithm") : null;
|
|
373
|
+
const dm = m ? kid(m, NS.ds, "DigestMethod") : null;
|
|
374
|
+
const digest = OAEP_DIGEST[(dm && attr(dm, "Algorithm")) ?? HASH_SHA1];
|
|
375
|
+
let mgf;
|
|
376
|
+
if (alg === `${NS.xenc}rsa-oaep-mgf1p`)
|
|
377
|
+
mgf = "sha1";
|
|
378
|
+
else if (alg === `${NS.xenc11}rsa-oaep`) {
|
|
379
|
+
const g = kid(m, NS.xenc11, "MGF");
|
|
380
|
+
mgf = OAEP_MGF[(g && attr(g, "Algorithm")) ?? `${NS.xenc11}mgf1sha1`];
|
|
381
|
+
}
|
|
382
|
+
else
|
|
383
|
+
continue;
|
|
384
|
+
if (!digest || digest !== mgf || kid(m, NS.xenc, "OAEPparams"))
|
|
385
|
+
continue;
|
|
386
|
+
const cd = kid(ek, NS.xenc, "CipherData");
|
|
387
|
+
const cv = cd ? kid(cd, NS.xenc, "CipherValue") : null;
|
|
388
|
+
if (!cv)
|
|
389
|
+
continue;
|
|
390
|
+
const enc = base64(text(cv, 8192), "an encrypted key");
|
|
391
|
+
for (const k of keys) {
|
|
392
|
+
try {
|
|
393
|
+
const out = privateDecrypt({ key: k.key, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: digest }, enc);
|
|
394
|
+
if (out.length === keyLength) {
|
|
395
|
+
cek = out;
|
|
396
|
+
break outer;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (!cek)
|
|
404
|
+
return unable();
|
|
405
|
+
const cd = kid(d, NS.xenc, "CipherData");
|
|
406
|
+
const cv = cd ? kid(cd, NS.xenc, "CipherValue") : null;
|
|
407
|
+
if (!cv)
|
|
408
|
+
fail("the encrypted part has no cipher value");
|
|
409
|
+
const bytes = base64(text(cv, 4 * MAX_SAML_RESPONSE), "the encrypted part");
|
|
410
|
+
let plain;
|
|
411
|
+
try {
|
|
412
|
+
if (mode === "gcm") {
|
|
413
|
+
if (bytes.length < 12 + 16)
|
|
414
|
+
unable();
|
|
415
|
+
const dec = createDecipheriv(cipherName, cek, bytes.subarray(0, 12));
|
|
416
|
+
dec.setAuthTag(bytes.subarray(bytes.length - 16));
|
|
417
|
+
plain = Buffer.concat([dec.update(bytes.subarray(12, bytes.length - 16)), dec.final()]);
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
if (bytes.length < 32 || bytes.length % 16 !== 0)
|
|
421
|
+
unable();
|
|
422
|
+
const dec = createDecipheriv(cipherName, cek, bytes.subarray(0, 16));
|
|
423
|
+
dec.setAutoPadding(false);
|
|
424
|
+
const p = Buffer.concat([dec.update(bytes.subarray(16)), dec.final()]);
|
|
425
|
+
const pad = p[p.length - 1];
|
|
426
|
+
if (pad < 1 || pad > 16)
|
|
427
|
+
unable();
|
|
428
|
+
plain = p.subarray(0, p.length - pad);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
catch (err) {
|
|
432
|
+
if (err instanceof SignInError)
|
|
433
|
+
throw err;
|
|
434
|
+
return unable();
|
|
435
|
+
}
|
|
436
|
+
let out;
|
|
437
|
+
try {
|
|
438
|
+
out = utf8.decode(plain);
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
return unable();
|
|
442
|
+
}
|
|
443
|
+
return out.replace(/^\s*<\?xml[^>]*\?>/, "");
|
|
444
|
+
}
|
|
445
|
+
function decryptedElement(holder, keys, cbcAllowed) {
|
|
446
|
+
const plain = decrypt(holder, keys, cbcAllowed);
|
|
447
|
+
const xml = `<Decrypted${namespacesAt(holder.parentNode)}>${plain}</Decrypted>`;
|
|
448
|
+
const box = parseXml(xml, "the decrypted part");
|
|
449
|
+
const inner = elementChildren(box);
|
|
450
|
+
if (inner.length !== 1)
|
|
451
|
+
fail("the decrypted part must be one element");
|
|
452
|
+
return { xml, el: inner[0] };
|
|
453
|
+
}
|
|
454
|
+
function decodeResponse(raw) {
|
|
455
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > MAX_SAML_RESPONSE)
|
|
456
|
+
fail("no response, or too large");
|
|
457
|
+
try {
|
|
458
|
+
return utf8.decode(base64(raw, "the response"));
|
|
459
|
+
}
|
|
460
|
+
catch (err) {
|
|
461
|
+
if (err instanceof SignInError)
|
|
462
|
+
throw err;
|
|
463
|
+
return fail("the response is not UTF-8");
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
export function verifySamlResponse(c, response, o) {
|
|
467
|
+
const xml = decodeResponse(response);
|
|
468
|
+
const root = parseXml(xml, "the response");
|
|
469
|
+
if (!is(root, NS.proto, "Response"))
|
|
470
|
+
fail("not a SAML response");
|
|
471
|
+
const status = kid(root, NS.proto, "Status");
|
|
472
|
+
const code = status ? kid(status, NS.proto, "StatusCode") : null;
|
|
473
|
+
const value = code ? attr(code, "Value") : null;
|
|
474
|
+
if (value !== SUCCESS) {
|
|
475
|
+
const sub = code ? kid(code, NS.proto, "StatusCode") : null;
|
|
476
|
+
const why = sub ? attr(sub, "Value") : null;
|
|
477
|
+
if (why !== null && DENIED.has(why))
|
|
478
|
+
throw new SignInError("denied", "saml: the identity provider refused the sign-in");
|
|
479
|
+
fail(`the identity provider answered ${value ?? "no status"}`);
|
|
480
|
+
}
|
|
481
|
+
const plainAll = descendants(root, NS.saml, "Assertion");
|
|
482
|
+
const encryptedAll = descendants(root, NS.saml, "EncryptedAssertion");
|
|
483
|
+
if (plainAll.length + encryptedAll.length !== 1)
|
|
484
|
+
fail("a response must hold exactly one assertion");
|
|
485
|
+
const held = plainAll[0] ?? encryptedAll[0];
|
|
486
|
+
if (held.parentNode !== root)
|
|
487
|
+
fail("the assertion is not where a response keeps it");
|
|
488
|
+
const rSig = kid(root, NS.ds, "Signature");
|
|
489
|
+
const signedResponse = rSig ? verifiedCopy(xml, rSig, c, o.now) : null;
|
|
490
|
+
if (rSig && !signedResponse)
|
|
491
|
+
fail("the response's signature does not verify");
|
|
492
|
+
let assertionXml = xml;
|
|
493
|
+
let assertion;
|
|
494
|
+
if (encryptedAll.length === 1) {
|
|
495
|
+
const holder = signedResponse ? kids(signedResponse, NS.saml, "EncryptedAssertion") : [held];
|
|
496
|
+
if (holder.length !== 1)
|
|
497
|
+
fail("a response must hold exactly one assertion");
|
|
498
|
+
const out = decryptedElement(holder[0], o.keys, signedResponse !== null);
|
|
499
|
+
if (!is(out.el, NS.saml, "Assertion"))
|
|
500
|
+
fail("the encrypted part is not an assertion");
|
|
501
|
+
if (descendants(out.el, NS.saml, "Assertion").length !== 1)
|
|
502
|
+
fail("a response must hold exactly one assertion");
|
|
503
|
+
assertionXml = out.xml;
|
|
504
|
+
assertion = out.el;
|
|
505
|
+
}
|
|
506
|
+
else {
|
|
507
|
+
assertion = held;
|
|
508
|
+
}
|
|
509
|
+
const aSig = kid(assertion, NS.ds, "Signature");
|
|
510
|
+
let a;
|
|
511
|
+
if (aSig) {
|
|
512
|
+
const copy = verifiedCopy(assertionXml, aSig, c, o.now);
|
|
513
|
+
if (!copy)
|
|
514
|
+
fail("the assertion's signature does not verify");
|
|
515
|
+
a = copy;
|
|
516
|
+
}
|
|
517
|
+
else if (signedResponse) {
|
|
518
|
+
if (encryptedAll.length === 1) {
|
|
519
|
+
a = assertion;
|
|
520
|
+
}
|
|
521
|
+
else {
|
|
522
|
+
const inner = kids(signedResponse, NS.saml, "Assertion");
|
|
523
|
+
if (inner.length !== 1)
|
|
524
|
+
fail("a response must hold exactly one assertion");
|
|
525
|
+
a = inner[0];
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
fail("the response is not signed");
|
|
530
|
+
}
|
|
531
|
+
const envelope = signedResponse ?? root;
|
|
532
|
+
const issuerOf = (el) => {
|
|
533
|
+
const i = kid(el, NS.saml, "Issuer");
|
|
534
|
+
return i ? text(i) : null;
|
|
535
|
+
};
|
|
536
|
+
const rIssuer = issuerOf(envelope);
|
|
537
|
+
if (rIssuer !== null && rIssuer !== c.idpEntityId)
|
|
538
|
+
fail("the response comes from another identity provider");
|
|
539
|
+
const destination = attr(envelope, "Destination");
|
|
540
|
+
if (destination !== null && destination !== o.acsUrl)
|
|
541
|
+
fail("the response was sent to another address");
|
|
542
|
+
if (attr(a, "Version") !== "2.0")
|
|
543
|
+
fail("not a SAML 2.0 assertion");
|
|
544
|
+
const assertionId = attr(a, "ID");
|
|
545
|
+
if (!assertionId || assertionId.length > 256)
|
|
546
|
+
fail("the assertion has no id");
|
|
547
|
+
if (issuerOf(a) !== c.idpEntityId)
|
|
548
|
+
fail("the assertion comes from another identity provider");
|
|
549
|
+
const now = o.now;
|
|
550
|
+
const issued = time(attr(a, "IssueInstant"), "IssueInstant");
|
|
551
|
+
if (issued === null || issued > now + o.skewMs || issued < now - o.maxAgeMs - o.skewMs)
|
|
552
|
+
fail("the assertion is not fresh");
|
|
553
|
+
const conditions = kid(a, NS.saml, "Conditions");
|
|
554
|
+
if (!conditions)
|
|
555
|
+
fail("the assertion has no conditions");
|
|
556
|
+
const notBefore = time(attr(conditions, "NotBefore"), "NotBefore");
|
|
557
|
+
const notOnOrAfter = time(attr(conditions, "NotOnOrAfter"), "NotOnOrAfter");
|
|
558
|
+
if (notBefore !== null && notBefore > now + o.skewMs)
|
|
559
|
+
fail("the assertion is not valid yet");
|
|
560
|
+
if (notOnOrAfter !== null && notOnOrAfter <= now - o.skewMs)
|
|
561
|
+
fail("the assertion has expired");
|
|
562
|
+
const restrictions = kids(conditions, NS.saml, "AudienceRestriction");
|
|
563
|
+
if (restrictions.length === 0)
|
|
564
|
+
fail("the assertion names no audience");
|
|
565
|
+
for (const r of restrictions) {
|
|
566
|
+
if (!kids(r, NS.saml, "Audience").some((x) => text(x) === o.spEntityId))
|
|
567
|
+
fail("the assertion is meant for another service");
|
|
568
|
+
}
|
|
569
|
+
const subject = kid(a, NS.saml, "Subject");
|
|
570
|
+
if (!subject)
|
|
571
|
+
fail("the assertion has no subject");
|
|
572
|
+
let nameIdEl = kid(subject, NS.saml, "NameID");
|
|
573
|
+
const encId = kid(subject, NS.saml, "EncryptedID");
|
|
574
|
+
if (encId) {
|
|
575
|
+
if (nameIdEl)
|
|
576
|
+
fail("both a NameID and an EncryptedID");
|
|
577
|
+
const out = decryptedElement(encId, o.keys, true);
|
|
578
|
+
if (!is(out.el, NS.saml, "NameID"))
|
|
579
|
+
fail("the EncryptedID is not a NameID");
|
|
580
|
+
nameIdEl = out.el;
|
|
581
|
+
}
|
|
582
|
+
const nameId = nameIdEl ? text(nameIdEl) : null;
|
|
583
|
+
const nameIdFormat = nameIdEl ? (attr(nameIdEl, "Format") ?? UNSPECIFIED) : null;
|
|
584
|
+
let inResponseTo = null;
|
|
585
|
+
let expires = 0;
|
|
586
|
+
for (const sc of kids(subject, NS.saml, "SubjectConfirmation")) {
|
|
587
|
+
if (attr(sc, "Method") !== BEARER)
|
|
588
|
+
continue;
|
|
589
|
+
const d = kid(sc, NS.saml, "SubjectConfirmationData");
|
|
590
|
+
if (!d || attr(d, "Recipient") !== o.acsUrl)
|
|
591
|
+
continue;
|
|
592
|
+
const until = time(attr(d, "NotOnOrAfter"), "NotOnOrAfter");
|
|
593
|
+
const from = time(attr(d, "NotBefore"), "NotBefore");
|
|
594
|
+
const answers = attr(d, "InResponseTo");
|
|
595
|
+
if (until === null || until <= now - o.skewMs || from !== null || !answers)
|
|
596
|
+
continue;
|
|
597
|
+
inResponseTo = answers;
|
|
598
|
+
expires = until + o.skewMs;
|
|
599
|
+
break;
|
|
600
|
+
}
|
|
601
|
+
if (inResponseTo === null)
|
|
602
|
+
fail("no bearer confirmation for this service and a sign-in it started");
|
|
603
|
+
const rAnswers = attr(envelope, "InResponseTo");
|
|
604
|
+
if (rAnswers !== null && rAnswers !== inResponseTo)
|
|
605
|
+
fail("the response answers another request");
|
|
606
|
+
const authn = kid(a, NS.saml, "AuthnStatement");
|
|
607
|
+
if (!authn)
|
|
608
|
+
fail("the assertion does not say the person signed in");
|
|
609
|
+
const attributes = {};
|
|
610
|
+
let count = 0;
|
|
611
|
+
for (const st of kids(a, NS.saml, "AttributeStatement")) {
|
|
612
|
+
for (const at of kids(st, NS.saml, "Attribute")) {
|
|
613
|
+
const name = attr(at, "Name");
|
|
614
|
+
if (!name || name.length > 256)
|
|
615
|
+
continue;
|
|
616
|
+
if (++count > MAX_ATTRIBUTES)
|
|
617
|
+
fail("too many attributes");
|
|
618
|
+
const values = kids(at, NS.saml, "AttributeValue").map((v) => text(v));
|
|
619
|
+
if (values.length > MAX_VALUES)
|
|
620
|
+
fail("too many attribute values");
|
|
621
|
+
attributes[name] = [...(attributes[name] ?? []), ...values];
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const first = (names) => {
|
|
625
|
+
for (const n of names) {
|
|
626
|
+
const v = attributes[n]?.find((x) => x !== "");
|
|
627
|
+
if (v !== undefined)
|
|
628
|
+
return v;
|
|
629
|
+
}
|
|
630
|
+
return null;
|
|
631
|
+
};
|
|
632
|
+
let subjectValue;
|
|
633
|
+
if (c.subjectAttribute) {
|
|
634
|
+
const v = attributes[c.subjectAttribute] ?? [];
|
|
635
|
+
if (v.length !== 1)
|
|
636
|
+
fail(`the attribute ${c.subjectAttribute} must have exactly one value`);
|
|
637
|
+
subjectValue = v[0];
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
if (nameIdFormat === TRANSIENT)
|
|
641
|
+
fail("a transient NameID changes every sign-in; set subjectAttribute");
|
|
642
|
+
subjectValue = nameId;
|
|
643
|
+
}
|
|
644
|
+
if (!subjectValue)
|
|
645
|
+
fail("the assertion has no subject value");
|
|
646
|
+
let email = first(o.emailNames) ?? (nameIdFormat === EMAIL_FORMAT ? nameId : null);
|
|
647
|
+
if (email !== null && (email.length > 254 || !EMAIL.test(email)))
|
|
648
|
+
email = null;
|
|
649
|
+
const domain = email ? email.slice(email.lastIndexOf("@") + 1).toLowerCase() : null;
|
|
650
|
+
if (email !== null)
|
|
651
|
+
email = `${email.slice(0, email.lastIndexOf("@"))}@${domain}`;
|
|
652
|
+
const emailVerified = domain !== null && c.emailDomains.includes(domain);
|
|
653
|
+
const given = first(["givenName", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname", "urn:oid:2.5.4.42"]);
|
|
654
|
+
const family = first(["sn", "surname", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname", "urn:oid:2.5.4.4"]);
|
|
655
|
+
const name = first(o.nameNames) ?? (given || family ? [given, family].filter(Boolean).join(" ") : null);
|
|
656
|
+
const identity = {
|
|
657
|
+
provider: `saml:${c.id}`,
|
|
658
|
+
subject: subjectValue,
|
|
659
|
+
email,
|
|
660
|
+
emailVerified,
|
|
661
|
+
name,
|
|
662
|
+
picture: null,
|
|
663
|
+
claims: {
|
|
664
|
+
connection: c.id,
|
|
665
|
+
tenant: c.tenant ?? null,
|
|
666
|
+
issuer: c.idpEntityId,
|
|
667
|
+
nameId,
|
|
668
|
+
nameIdFormat,
|
|
669
|
+
nameQualifier: nameIdEl ? attr(nameIdEl, "NameQualifier") : null,
|
|
670
|
+
spNameQualifier: nameIdEl ? attr(nameIdEl, "SPNameQualifier") : null,
|
|
671
|
+
sessionIndex: attr(authn, "SessionIndex"),
|
|
672
|
+
attributes,
|
|
673
|
+
},
|
|
674
|
+
};
|
|
675
|
+
return { identity, inResponseTo, assertionId, expires };
|
|
676
|
+
}
|
|
677
|
+
export function samlSessionRef(identity) {
|
|
678
|
+
const k = identity.claims;
|
|
679
|
+
if (typeof k.connection !== "string" || typeof k.nameId !== "string")
|
|
680
|
+
return null;
|
|
681
|
+
const ref = {
|
|
682
|
+
c: k.connection,
|
|
683
|
+
n: k.nameId,
|
|
684
|
+
f: typeof k.nameIdFormat === "string" ? k.nameIdFormat : null,
|
|
685
|
+
s: typeof k.sessionIndex === "string" ? k.sessionIndex : null,
|
|
686
|
+
};
|
|
687
|
+
if (typeof k.nameQualifier === "string")
|
|
688
|
+
ref.nq = k.nameQualifier;
|
|
689
|
+
if (typeof k.spNameQualifier === "string")
|
|
690
|
+
ref.spnq = k.spNameQualifier;
|
|
691
|
+
return ref;
|
|
692
|
+
}
|
|
693
|
+
export function parseIdpMetadata(xml, o = {}) {
|
|
694
|
+
if (typeof xml !== "string" || xml.length > 1 << 20)
|
|
695
|
+
throw new TypeError("saml: metadata must be a string under 1 MiB");
|
|
696
|
+
let root;
|
|
697
|
+
try {
|
|
698
|
+
root = parseXml(xml, "the metadata");
|
|
699
|
+
}
|
|
700
|
+
catch (err) {
|
|
701
|
+
throw new TypeError(err instanceof Error ? err.message : String(err));
|
|
702
|
+
}
|
|
703
|
+
const entities = is(root, NS.md, "EntityDescriptor") ? [root] : descendants(root, NS.md, "EntityDescriptor");
|
|
704
|
+
const idps = entities.filter((e) => kids(e, NS.md, "IDPSSODescriptor").length > 0 && (!o.entityId || attr(e, "entityID") === o.entityId));
|
|
705
|
+
if (idps.length !== 1)
|
|
706
|
+
throw new TypeError(idps.length === 0 ? "saml: no identity provider in the metadata" : "saml: several identity providers; pass entityId");
|
|
707
|
+
const e = idps[0];
|
|
708
|
+
const entityId = attr(e, "entityID");
|
|
709
|
+
if (!entityId)
|
|
710
|
+
throw new TypeError("saml: the metadata has no entityID");
|
|
711
|
+
const idp = kids(e, NS.md, "IDPSSODescriptor")[0];
|
|
712
|
+
const redirect = (name) => kids(idp, NS.md, name).find((s) => attr(s, "Binding") === REDIRECT_BINDING) ?? null;
|
|
713
|
+
const sso = redirect("SingleSignOnService");
|
|
714
|
+
const ssoUrl = sso ? attr(sso, "Location") : null;
|
|
715
|
+
if (!ssoUrl)
|
|
716
|
+
throw new TypeError("saml: the identity provider offers no HTTP-Redirect sign-on");
|
|
717
|
+
const slo = redirect("SingleLogoutService");
|
|
718
|
+
const certificates = [];
|
|
719
|
+
for (const kd of kids(idp, NS.md, "KeyDescriptor")) {
|
|
720
|
+
const use = attr(kd, "use");
|
|
721
|
+
if (use !== null && use !== "signing")
|
|
722
|
+
continue;
|
|
723
|
+
for (const c of descendants(kd, NS.ds, "X509Certificate"))
|
|
724
|
+
certificates.push(readCert(c.textContent ?? "").pem);
|
|
725
|
+
}
|
|
726
|
+
if (certificates.length === 0)
|
|
727
|
+
throw new TypeError("saml: the metadata has no signing certificate");
|
|
728
|
+
const sloLocation = slo ? attr(slo, "Location") : null;
|
|
729
|
+
const sloResponse = slo ? attr(slo, "ResponseLocation") : null;
|
|
730
|
+
return {
|
|
731
|
+
entityId,
|
|
732
|
+
ssoUrl: checkEndpoint(ssoUrl, "the metadata's sign-on URL"),
|
|
733
|
+
sloUrl: sloLocation ? checkEndpoint(sloLocation, "the metadata's logout URL") : null,
|
|
734
|
+
sloResponseUrl: sloResponse ? checkEndpoint(sloResponse, "the metadata's logout response URL") : null,
|
|
735
|
+
certificates,
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
export function defineSaml(o) {
|
|
739
|
+
if (typeof o?.connection !== "function")
|
|
740
|
+
throw new TypeError("defineSaml: connection(id) is required");
|
|
741
|
+
const skew = o.skewSeconds ?? 60;
|
|
742
|
+
if (!Number.isFinite(skew) || skew < 0 || skew > 600)
|
|
743
|
+
throw new TypeError("defineSaml: skewSeconds is 0-600");
|
|
744
|
+
const maxAge = o.maxAgeSeconds ?? 300;
|
|
745
|
+
if (!Number.isFinite(maxAge) || maxAge <= 0 || maxAge > 3600)
|
|
746
|
+
throw new TypeError("defineSaml: maxAgeSeconds is 1-3600");
|
|
747
|
+
if (o.sp !== undefined && (!Array.isArray(o.sp.keys) || o.sp.keys.length === 0 || o.sp.keys.length > 4)) {
|
|
748
|
+
throw new TypeError("defineSaml: sp.keys is 1-4 key pairs, the current one first");
|
|
749
|
+
}
|
|
750
|
+
if (o.userFor !== undefined && typeof o.userFor !== "function")
|
|
751
|
+
throw new TypeError("defineSaml: userFor must be a function");
|
|
752
|
+
const keys = (o.sp?.keys ?? []).map(readSpKey);
|
|
753
|
+
const current = keys[0] ?? null;
|
|
754
|
+
const emailNames = o.attributes?.email ?? DEFAULT_EMAIL;
|
|
755
|
+
const nameNames = o.attributes?.name ?? DEFAULT_NAME;
|
|
756
|
+
const now = o.now ?? Date.now;
|
|
757
|
+
const seen = new Map();
|
|
758
|
+
const memory = {
|
|
759
|
+
claim(key, until) {
|
|
760
|
+
const t = now();
|
|
761
|
+
if (seen.size > 10_000)
|
|
762
|
+
for (const [k, u] of seen)
|
|
763
|
+
if (u <= t)
|
|
764
|
+
seen.delete(k);
|
|
765
|
+
if (seen.size > 200_000)
|
|
766
|
+
return false;
|
|
767
|
+
const was = seen.get(key);
|
|
768
|
+
if (was !== undefined && was > t)
|
|
769
|
+
return false;
|
|
770
|
+
seen.set(key, until);
|
|
771
|
+
return true;
|
|
772
|
+
},
|
|
773
|
+
};
|
|
774
|
+
const replay = o.replay ?? memory;
|
|
775
|
+
const origin = (base) => new URL(base).origin;
|
|
776
|
+
const signsRequests = (c) => current !== null && c.signRequests !== false;
|
|
777
|
+
const certInfo = (use, x, t) => ({
|
|
778
|
+
use,
|
|
779
|
+
subject: x.subject,
|
|
780
|
+
fingerprint256: x.fingerprint256,
|
|
781
|
+
notBefore: new Date(x.notBefore),
|
|
782
|
+
notAfter: new Date(x.notAfter),
|
|
783
|
+
daysLeft: Math.floor((x.notAfter - t) / DAY),
|
|
784
|
+
valid: x.notBefore <= t && t < x.notAfter,
|
|
785
|
+
});
|
|
786
|
+
const keyDescriptor = (use, x) => ` <md:KeyDescriptor use="${use}"><ds:KeyInfo><ds:X509Data><ds:X509Certificate>` +
|
|
787
|
+
x.pem.replace(/-----[^-]+-----|\s/g, "") +
|
|
788
|
+
`</ds:X509Certificate></ds:X509Data></ds:KeyInfo>` +
|
|
789
|
+
(use === "encryption"
|
|
790
|
+
? `<md:EncryptionMethod Algorithm="${NS.xenc11}aes256-gcm"/><md:EncryptionMethod Algorithm="${NS.xenc11}aes128-gcm"/>` +
|
|
791
|
+
`<md:EncryptionMethod Algorithm="${NS.xenc}rsa-oaep-mgf1p"/>`
|
|
792
|
+
: "") +
|
|
793
|
+
`</md:KeyDescriptor>\n`;
|
|
794
|
+
function checkLogoutEnvelope(el, c, base) {
|
|
795
|
+
const t = now();
|
|
796
|
+
if (attr(el, "Version") !== "2.0")
|
|
797
|
+
fail("not a SAML 2.0 message");
|
|
798
|
+
const id = attr(el, "ID");
|
|
799
|
+
if (!id || id.length > 256)
|
|
800
|
+
fail("the message has no id");
|
|
801
|
+
const issuer = kid(el, NS.saml, "Issuer");
|
|
802
|
+
if (!issuer || text(issuer) !== c.idpEntityId)
|
|
803
|
+
fail("the message comes from another identity provider");
|
|
804
|
+
const destination = attr(el, "Destination");
|
|
805
|
+
if (destination !== null && destination !== saml.sloUrl(base, c.id))
|
|
806
|
+
fail("the message was sent to another address");
|
|
807
|
+
const issued = time(attr(el, "IssueInstant"), "IssueInstant");
|
|
808
|
+
if (issued === null || issued > t + skew * 1000 || issued < t - (maxAge + skew) * 1000)
|
|
809
|
+
fail("the message is not fresh");
|
|
810
|
+
}
|
|
811
|
+
const saml = {
|
|
812
|
+
startPath(id, next) {
|
|
813
|
+
if (!SAML_ID.test(id))
|
|
814
|
+
throw new TypeError("saml: bad connection id");
|
|
815
|
+
return `${PATH}${id}${next ? `?next=${encodeURIComponent(next)}` : ""}`;
|
|
816
|
+
},
|
|
817
|
+
logoutPath: () => `${PATH}logout`,
|
|
818
|
+
spEntityId: (base, id) => `${origin(base)}${PATH}${id}`,
|
|
819
|
+
acsUrl: (base, id) => `${origin(base)}${PATH}${id}/acs`,
|
|
820
|
+
sloUrl: (base, id) => `${origin(base)}${PATH}${id}/slo`,
|
|
821
|
+
metadata(base, c) {
|
|
822
|
+
const slo = saml.sloUrl(base, c.id);
|
|
823
|
+
return (`<?xml version="1.0" encoding="UTF-8"?>\n` +
|
|
824
|
+
`<md:EntityDescriptor xmlns:md="${NS.md}" xmlns:ds="${NS.ds}" entityID="${escapeXml(saml.spEntityId(base, c.id))}">\n` +
|
|
825
|
+
` <md:SPSSODescriptor AuthnRequestsSigned="${signsRequests(c)}" WantAssertionsSigned="true" protocolSupportEnumeration="${NS.proto}">\n` +
|
|
826
|
+
(current ? keyDescriptor("signing", current.cert) + keyDescriptor("encryption", current.cert) : "") +
|
|
827
|
+
` <md:SingleLogoutService Binding="${REDIRECT_BINDING}" Location="${escapeXml(slo)}"/>\n` +
|
|
828
|
+
` <md:SingleLogoutService Binding="${POST_BINDING}" Location="${escapeXml(slo)}"/>\n` +
|
|
829
|
+
` <md:NameIDFormat>${escapeXml(c.nameIdFormat ?? UNSPECIFIED)}</md:NameIDFormat>\n` +
|
|
830
|
+
` <md:AssertionConsumerService Binding="${POST_BINDING}" Location="${escapeXml(saml.acsUrl(base, c.id))}" index="0" isDefault="true"/>\n` +
|
|
831
|
+
` </md:SPSSODescriptor>\n` +
|
|
832
|
+
`</md:EntityDescriptor>\n`);
|
|
833
|
+
},
|
|
834
|
+
describeCertificates(c) {
|
|
835
|
+
const t = now();
|
|
836
|
+
const idp = c.certificates.map((x) => (typeof x === "string" ? readCert(x) : x));
|
|
837
|
+
return [...idp.map((x) => certInfo("idp-signing", x, t)), ...keys.map((k) => certInfo("sp", k.cert, t))];
|
|
838
|
+
},
|
|
839
|
+
async resolve(id) {
|
|
840
|
+
if (!SAML_ID.test(id))
|
|
841
|
+
return null;
|
|
842
|
+
const c = await o.connection(id);
|
|
843
|
+
if (!c)
|
|
844
|
+
return null;
|
|
845
|
+
if (c.id !== id)
|
|
846
|
+
throw new TypeError(`saml: connection(${id}) returned connection ${c.id}`);
|
|
847
|
+
return checkSamlConnection(c);
|
|
848
|
+
},
|
|
849
|
+
authorize(c, { requestId, base }) {
|
|
850
|
+
const xml = `<samlp:AuthnRequest xmlns:samlp="${NS.proto}" xmlns:saml="${NS.saml}" ID="${requestId}" Version="2.0" ` +
|
|
851
|
+
`IssueInstant="${instant(now())}" Destination="${escapeXml(c.ssoUrl)}" ` +
|
|
852
|
+
`AssertionConsumerServiceURL="${escapeXml(saml.acsUrl(base, c.id))}" ProtocolBinding="${POST_BINDING}">` +
|
|
853
|
+
`<saml:Issuer>${escapeXml(saml.spEntityId(base, c.id))}</saml:Issuer>` +
|
|
854
|
+
`<samlp:NameIDPolicy Format="${escapeXml(c.nameIdFormat ?? UNSPECIFIED)}" AllowCreate="true"/>` +
|
|
855
|
+
`</samlp:AuthnRequest>`;
|
|
856
|
+
return redirectUrl(c.ssoUrl, "SAMLRequest", xml, null, signsRequests(c) ? current.key : null);
|
|
857
|
+
},
|
|
858
|
+
verify(c, response, { base }) {
|
|
859
|
+
return verifySamlResponse(c, response, {
|
|
860
|
+
acsUrl: saml.acsUrl(base, c.id),
|
|
861
|
+
spEntityId: saml.spEntityId(base, c.id),
|
|
862
|
+
now: now(),
|
|
863
|
+
skewMs: skew * 1000,
|
|
864
|
+
maxAgeMs: maxAge * 1000,
|
|
865
|
+
emailNames,
|
|
866
|
+
nameNames,
|
|
867
|
+
keys,
|
|
868
|
+
});
|
|
869
|
+
},
|
|
870
|
+
logoutRequest(c, ref, { requestId, base }) {
|
|
871
|
+
if (!c.sloUrl)
|
|
872
|
+
return null;
|
|
873
|
+
const q = `${ref.nq ? ` NameQualifier="${escapeXml(ref.nq)}"` : ""}${ref.spnq ? ` SPNameQualifier="${escapeXml(ref.spnq)}"` : ""}`;
|
|
874
|
+
const xml = `<samlp:LogoutRequest xmlns:samlp="${NS.proto}" xmlns:saml="${NS.saml}" ID="${requestId}" Version="2.0" ` +
|
|
875
|
+
`IssueInstant="${instant(now())}" Destination="${escapeXml(c.sloUrl)}" NotOnOrAfter="${instant(now() + maxAge * 1000)}">` +
|
|
876
|
+
`<saml:Issuer>${escapeXml(saml.spEntityId(base, c.id))}</saml:Issuer>` +
|
|
877
|
+
`<saml:NameID${ref.f ? ` Format="${escapeXml(ref.f)}"` : ""}${q}>${escapeXml(ref.n)}</saml:NameID>` +
|
|
878
|
+
(ref.s ? `<samlp:SessionIndex>${escapeXml(ref.s)}</samlp:SessionIndex>` : "") +
|
|
879
|
+
`</samlp:LogoutRequest>`;
|
|
880
|
+
return redirectUrl(c.sloUrl, "SAMLRequest", xml, null, current?.key ?? null);
|
|
881
|
+
},
|
|
882
|
+
logoutResponse(c, { inResponseTo, base, relay }) {
|
|
883
|
+
const to = c.sloResponseUrl ?? c.sloUrl;
|
|
884
|
+
if (!to)
|
|
885
|
+
return null;
|
|
886
|
+
const xml = `<samlp:LogoutResponse xmlns:samlp="${NS.proto}" xmlns:saml="${NS.saml}" ID="${saml.newRequestId()}" Version="2.0" ` +
|
|
887
|
+
`IssueInstant="${instant(now())}" Destination="${escapeXml(to)}" InResponseTo="${escapeXml(inResponseTo)}">` +
|
|
888
|
+
`<saml:Issuer>${escapeXml(saml.spEntityId(base, c.id))}</saml:Issuer>` +
|
|
889
|
+
`<samlp:Status><samlp:StatusCode Value="${SUCCESS}"/></samlp:Status>` +
|
|
890
|
+
`</samlp:LogoutResponse>`;
|
|
891
|
+
return redirectUrl(to, "SAMLResponse", xml, relay !== null && relay.length <= 1024 ? relay : null, current?.key ?? null);
|
|
892
|
+
},
|
|
893
|
+
readLogout(c, { search, form, base }) {
|
|
894
|
+
let el;
|
|
895
|
+
let relay;
|
|
896
|
+
if (form) {
|
|
897
|
+
const raw = form.get("SAMLRequest") ?? form.get("SAMLResponse");
|
|
898
|
+
if (raw === null || raw.length > MAX_SAML_RESPONSE)
|
|
899
|
+
fail("no SAML message");
|
|
900
|
+
const xml = utf8.decode(base64(raw, "the message"));
|
|
901
|
+
const root = parseXml(xml, "the message");
|
|
902
|
+
const sig = kid(root, NS.ds, "Signature");
|
|
903
|
+
if (!sig)
|
|
904
|
+
fail("the message is not signed");
|
|
905
|
+
const copy = verifiedCopy(xml, sig, c, now());
|
|
906
|
+
if (!copy)
|
|
907
|
+
fail("the message's signature does not verify");
|
|
908
|
+
el = copy;
|
|
909
|
+
relay = form.get("RelayState");
|
|
910
|
+
}
|
|
911
|
+
else {
|
|
912
|
+
const r = readRedirect(search, c, now());
|
|
913
|
+
el = parseXml(r.xml, "the message");
|
|
914
|
+
relay = r.relay;
|
|
915
|
+
}
|
|
916
|
+
checkLogoutEnvelope(el, c, base);
|
|
917
|
+
if (is(el, NS.proto, "LogoutRequest")) {
|
|
918
|
+
const t = now();
|
|
919
|
+
const until = time(attr(el, "NotOnOrAfter"), "NotOnOrAfter");
|
|
920
|
+
if (until !== null && until <= t - skew * 1000)
|
|
921
|
+
fail("the logout request has expired");
|
|
922
|
+
let nameIdEl = kid(el, NS.saml, "NameID");
|
|
923
|
+
const encId = kid(el, NS.saml, "EncryptedID");
|
|
924
|
+
if (encId) {
|
|
925
|
+
if (nameIdEl)
|
|
926
|
+
fail("both a NameID and an EncryptedID");
|
|
927
|
+
const out = decryptedElement(encId, keys, true);
|
|
928
|
+
if (!is(out.el, NS.saml, "NameID"))
|
|
929
|
+
fail("the EncryptedID is not a NameID");
|
|
930
|
+
nameIdEl = out.el;
|
|
931
|
+
}
|
|
932
|
+
if (!nameIdEl)
|
|
933
|
+
fail("the logout request names no one");
|
|
934
|
+
const nameId = text(nameIdEl);
|
|
935
|
+
if (nameId === "")
|
|
936
|
+
fail("the logout request names no one");
|
|
937
|
+
const sessionIndexes = kids(el, NS.proto, "SessionIndex").map((s) => text(s)).slice(0, 50);
|
|
938
|
+
return { kind: "request", id: attr(el, "ID"), nameId, sessionIndexes, relay, expires: t + (maxAge + skew) * 1000 };
|
|
939
|
+
}
|
|
940
|
+
if (is(el, NS.proto, "LogoutResponse")) {
|
|
941
|
+
const status = kid(el, NS.proto, "Status");
|
|
942
|
+
const code = status ? kid(status, NS.proto, "StatusCode") : null;
|
|
943
|
+
return { kind: "response", inResponseTo: attr(el, "InResponseTo"), success: code !== null && attr(code, "Value") === SUCCESS };
|
|
944
|
+
}
|
|
945
|
+
fail("not a logout message");
|
|
946
|
+
},
|
|
947
|
+
async userFor(subject) {
|
|
948
|
+
if (!o.userFor)
|
|
949
|
+
return null;
|
|
950
|
+
const u = await o.userFor(subject);
|
|
951
|
+
return typeof u === "string" && u !== "" ? u : null;
|
|
952
|
+
},
|
|
953
|
+
async claim(key, until) {
|
|
954
|
+
return (await replay.claim(key, until)) === true;
|
|
955
|
+
},
|
|
956
|
+
newRequestId: () => `_${randomBytes(20).toString("hex")}`,
|
|
957
|
+
};
|
|
958
|
+
return saml;
|
|
959
|
+
}
|