@hyper.authio/client 0.1.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -9
- package/dist/index.cjs +748 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +742 -110
- package/dist/index.d.ts +742 -110
- package/dist/index.js +725 -49
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { compactDecrypt, createRemoteJWKSet, customFetch, jwtVerify, importPKCS8, SignJWT, importJWK } from 'jose';
|
|
1
|
+
import { compactDecrypt, errors, decodeProtectedHeader, createRemoteJWKSet, customFetch, jwtVerify, importPKCS8, SignJWT, importJWK } from 'jose';
|
|
2
2
|
|
|
3
3
|
// src/constants.ts
|
|
4
4
|
var AuthioClaimTypes = {
|
|
@@ -18,6 +18,8 @@ var AuthioClaimTypes = {
|
|
|
18
18
|
AuthenticationMethods: "amr",
|
|
19
19
|
IdentityProvider: "idp",
|
|
20
20
|
Nonce: "nonce",
|
|
21
|
+
AccessTokenHash: "at_hash",
|
|
22
|
+
Events: "events",
|
|
21
23
|
OrganizationId: "org_id",
|
|
22
24
|
OrganizationAlias: "org_alias",
|
|
23
25
|
AccountId: "account_id",
|
|
@@ -37,6 +39,12 @@ var AuthioClaimTypes = {
|
|
|
37
39
|
ConsumerName: "consumer_name",
|
|
38
40
|
CredentialId: "credential_id",
|
|
39
41
|
CredentialType: "credential_type",
|
|
42
|
+
CredentialName: "credential_name",
|
|
43
|
+
CredentialRealm: "credential_realm",
|
|
44
|
+
CredentialClient: "credential_client",
|
|
45
|
+
ActorType: "actor_type",
|
|
46
|
+
OwnerUserId: "owner_user_id",
|
|
47
|
+
OwnerUsername: "owner_username",
|
|
40
48
|
UserResourceAccess: "user_resource_access",
|
|
41
49
|
RealmResourceAccess: "realm_resource_access",
|
|
42
50
|
ClientResourceAccess: "client_resource_access",
|
|
@@ -94,7 +102,13 @@ var AuthioOAuthErrors = {
|
|
|
94
102
|
ConnectionSelectionRequired: "connection_selection_required",
|
|
95
103
|
ConnectionPolicyViolation: "connection_policy_violation",
|
|
96
104
|
ServerError: "server_error",
|
|
97
|
-
TemporarilyUnavailable: "temporarily_unavailable"
|
|
105
|
+
TemporarilyUnavailable: "temporarily_unavailable",
|
|
106
|
+
LoginRequired: "login_required",
|
|
107
|
+
InteractionRequired: "interaction_required",
|
|
108
|
+
ConsentRequired: "consent_required",
|
|
109
|
+
AccountSelectionRequired: "account_selection_required",
|
|
110
|
+
InsufficientScope: "insufficient_scope",
|
|
111
|
+
InsufficientUserAuthentication: "insufficient_user_authentication"
|
|
98
112
|
};
|
|
99
113
|
var AuthioWebhookEventTypes = {
|
|
100
114
|
UserCreated: "user_created",
|
|
@@ -111,6 +125,8 @@ var AuthioWebhookEventTypes = {
|
|
|
111
125
|
AdminResourceDeleted: "admin_resource_deleted",
|
|
112
126
|
UserSuspended: "user_suspended",
|
|
113
127
|
UserSuspensionEnded: "user_suspension_ended",
|
|
128
|
+
AttackDetected: "attack_detected",
|
|
129
|
+
CredentialCompromised: "credential_compromised",
|
|
114
130
|
Ping: "ping"
|
|
115
131
|
};
|
|
116
132
|
var AuthioWebhookHeaders = {
|
|
@@ -118,6 +134,8 @@ var AuthioWebhookHeaders = {
|
|
|
118
134
|
Event: "X-Authio-Event",
|
|
119
135
|
EventId: "X-Authio-Event-Id"
|
|
120
136
|
};
|
|
137
|
+
var AuthioCallerKinds = ["user", "client", "consumer", "account_credential"];
|
|
138
|
+
var AuthioPrompts = ["none", "login", "select_account", "consent"];
|
|
121
139
|
var AuthioAsymmetricAlgorithms = [
|
|
122
140
|
"RS256",
|
|
123
141
|
"RS384",
|
|
@@ -131,12 +149,23 @@ var AuthioAsymmetricAlgorithms = [
|
|
|
131
149
|
];
|
|
132
150
|
var AuthioDefaults = {
|
|
133
151
|
DiscoveryPath: "/.well-known/openid-configuration",
|
|
152
|
+
ProtectedResourceMetadataPath: "/.well-known/oauth-protected-resource",
|
|
134
153
|
RedactedValue: "[redacted]",
|
|
135
154
|
PlatformRealm: "authio",
|
|
136
155
|
PlatformClientId: "authio",
|
|
137
156
|
ApiKeyPrefix: "ak_",
|
|
138
157
|
ClientSecretPrefix: "cs_",
|
|
139
158
|
PersonalAccessTokenPrefix: "pat_",
|
|
159
|
+
/** The `client_id` an account credential's client secret is exchanged with: `cred_` and the credential id (format N). */
|
|
160
|
+
CredentialClientIdPrefix: "cred_",
|
|
161
|
+
ApiKeyHeader: "x-api-key",
|
|
162
|
+
RequestIdHeader: "X-Request-Id",
|
|
163
|
+
/** The header `typ` of a back-channel logout token. */
|
|
164
|
+
LogoutTokenType: "logout+jwt",
|
|
165
|
+
/** The event a back-channel logout token carries. */
|
|
166
|
+
BackchannelLogoutEvent: "http://schemas.openid.net/event/backchannel-logout",
|
|
167
|
+
/** Seconds. */
|
|
168
|
+
ClockSkew: 30,
|
|
140
169
|
/** Seconds. */
|
|
141
170
|
ClientAssertionLifetime: 120,
|
|
142
171
|
/** Seconds. */
|
|
@@ -188,6 +217,47 @@ var AuthioDiscoveryError = class extends AuthioError {
|
|
|
188
217
|
};
|
|
189
218
|
var AuthioConfigurationError = class extends AuthioError {
|
|
190
219
|
};
|
|
220
|
+
var AuthioTokenValidationError = class extends AuthioError {
|
|
221
|
+
/** Why, as a stable code. */
|
|
222
|
+
reason;
|
|
223
|
+
constructor(reason, message, options) {
|
|
224
|
+
super(message, options);
|
|
225
|
+
this.reason = reason;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
var AuthioCallbackError = class extends AuthioError {
|
|
229
|
+
/** Why, as a stable code. */
|
|
230
|
+
reason;
|
|
231
|
+
constructor(reason, message) {
|
|
232
|
+
super(message);
|
|
233
|
+
this.reason = reason;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
var AuthioAdminError = class extends AuthioError {
|
|
237
|
+
/** The HTTP status. */
|
|
238
|
+
status;
|
|
239
|
+
/** Authio's error code, such as `ValidationFailed` or `RealmNotFound`. */
|
|
240
|
+
errorCode;
|
|
241
|
+
/** The messages, with the field each one is about. */
|
|
242
|
+
notifications;
|
|
243
|
+
/** The request id, from the envelope or the `X-Request-Id` header. */
|
|
244
|
+
requestId;
|
|
245
|
+
/** Seconds to wait before retrying, from `Retry-After` (`429` and `503`). */
|
|
246
|
+
retryAfterSeconds;
|
|
247
|
+
constructor(details) {
|
|
248
|
+
const notifications = details.notifications ?? [];
|
|
249
|
+
const summary = notifications.map((notification) => notification.message).filter(Boolean).join(" ");
|
|
250
|
+
super(
|
|
251
|
+
`The Authio Admin API answered HTTP ${details.status}${details.errorCode ? ` (${details.errorCode})` : ""}${summary ? `: ${summary}` : "."}`,
|
|
252
|
+
{ cause: details.cause }
|
|
253
|
+
);
|
|
254
|
+
this.status = details.status;
|
|
255
|
+
this.errorCode = details.errorCode;
|
|
256
|
+
this.notifications = Object.freeze([...notifications]);
|
|
257
|
+
this.requestId = details.requestId;
|
|
258
|
+
this.retryAfterSeconds = details.retryAfterSeconds;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
191
261
|
|
|
192
262
|
// src/options.ts
|
|
193
263
|
var systemClock = {
|
|
@@ -534,17 +604,22 @@ function createClientAuthenticator(settings, connection) {
|
|
|
534
604
|
`The Authio clientAssertionLifetime must be more than 0 and at most ${AuthioDefaults.MaxClientAssertionLifetime} seconds.`
|
|
535
605
|
);
|
|
536
606
|
const loadKey = method === "private_key_jwt" ? createKeyLoader(settings) : void 0;
|
|
607
|
+
const secret = async () => {
|
|
608
|
+
const value = typeof settings.clientSecret === "function" ? await settings.clientSecret() : settings.clientSecret;
|
|
609
|
+
if (typeof value !== "string" || !value) throw new AuthioConfigurationError("The Authio clientSecret function returned no secret.");
|
|
610
|
+
return value;
|
|
611
|
+
};
|
|
537
612
|
return {
|
|
538
613
|
clientId,
|
|
539
614
|
method,
|
|
540
615
|
async apply(form, headers) {
|
|
541
616
|
switch (method) {
|
|
542
617
|
case "client_secret_basic":
|
|
543
|
-
headers.set("authorization", toBasicAuthorization(clientId,
|
|
618
|
+
headers.set("authorization", toBasicAuthorization(clientId, await secret()));
|
|
544
619
|
return;
|
|
545
620
|
case "client_secret_post":
|
|
546
621
|
form.set("client_id", clientId);
|
|
547
|
-
form.set("client_secret",
|
|
622
|
+
form.set("client_secret", await secret());
|
|
548
623
|
return;
|
|
549
624
|
case "private_key_jwt":
|
|
550
625
|
form.set("client_id", clientId);
|
|
@@ -598,17 +673,20 @@ function createKeyLoader(settings) {
|
|
|
598
673
|
};
|
|
599
674
|
}
|
|
600
675
|
var AuthioKeyManagementAlgorithms = ["RSA-OAEP", "RSA-OAEP-256"];
|
|
676
|
+
var AuthioLegacyKeyManagementAlgorithms = ["RSA1_5"];
|
|
601
677
|
var AuthioContentEncryptionAlgorithms = ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"];
|
|
602
678
|
var rsaAlgorithmIdentifier = [48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0];
|
|
603
679
|
function isAuthioTokenEncrypted(token) {
|
|
604
680
|
return typeof token === "string" && token.split(".").length === 5;
|
|
605
681
|
}
|
|
606
|
-
function createAuthioTokenDecrypter(key,
|
|
682
|
+
function createAuthioTokenDecrypter(key, options = {}) {
|
|
683
|
+
const settings = typeof options === "string" ? { setting: options } : options;
|
|
684
|
+
const setting = settings.setting ?? "clientEncryptionKey";
|
|
607
685
|
const imported = /* @__PURE__ */ new Map();
|
|
608
686
|
const importFor = (algorithm) => {
|
|
609
687
|
let pending = imported.get(algorithm);
|
|
610
688
|
if (!pending) {
|
|
611
|
-
pending = importDecryptionKey(
|
|
689
|
+
pending = Promise.resolve(typeof key === "function" ? key() : key).then((value) => importDecryptionKey(value, algorithm, setting));
|
|
612
690
|
imported.set(algorithm, pending);
|
|
613
691
|
pending.catch(() => imported.delete(algorithm));
|
|
614
692
|
}
|
|
@@ -616,17 +694,59 @@ function createAuthioTokenDecrypter(key, setting = "clientEncryptionKey") {
|
|
|
616
694
|
};
|
|
617
695
|
return async (token) => {
|
|
618
696
|
if (!isAuthioTokenEncrypted(token)) return token;
|
|
619
|
-
|
|
620
|
-
|
|
697
|
+
const algorithm = algorithmOf(token);
|
|
698
|
+
if (AuthioLegacyKeyManagementAlgorithms.includes(algorithm))
|
|
699
|
+
throw new AuthioTokenValidationError(
|
|
700
|
+
"legacy_algorithm",
|
|
701
|
+
settings.allowLegacyEncryptionAlgorithms ? "The token is encrypted with RSA1_5 (PKCS#1 v1.5), which Node and WebCrypto cannot decrypt even with allowLegacyEncryptionAlgorithms; register RSA-OAEP-256 as the client's encryption algorithm in Authio." : "The token is encrypted with the legacy RSA1_5 algorithm, which is refused; register RSA-OAEP-256 as the client's encryption algorithm in Authio."
|
|
702
|
+
);
|
|
703
|
+
if (!AuthioKeyManagementAlgorithms.includes(algorithm))
|
|
704
|
+
throw new AuthioTokenValidationError(
|
|
705
|
+
"decryption_failed",
|
|
706
|
+
`The token is encrypted with '${algorithm}'; Authio encrypts with ${AuthioKeyManagementAlgorithms.join(" or ")}.`
|
|
707
|
+
);
|
|
708
|
+
if (key === void 0 || key === null || key === "")
|
|
709
|
+
throw new AuthioTokenValidationError(
|
|
710
|
+
"decryption_failed",
|
|
621
711
|
`Authio encrypted this token to the client's own key; set ${setting} to the private key Authio showed when it generated the pair.`
|
|
622
712
|
);
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
713
|
+
try {
|
|
714
|
+
const { plaintext } = await compactDecrypt(token, (header) => importFor(header.alg), {
|
|
715
|
+
keyManagementAlgorithms: [...AuthioKeyManagementAlgorithms],
|
|
716
|
+
contentEncryptionAlgorithms: [...AuthioContentEncryptionAlgorithms]
|
|
717
|
+
});
|
|
718
|
+
return new TextDecoder().decode(plaintext);
|
|
719
|
+
} catch (error) {
|
|
720
|
+
if (error instanceof AuthioConfigurationError) throw error;
|
|
721
|
+
if (error instanceof errors.JOSEError)
|
|
722
|
+
throw new AuthioTokenValidationError("decryption_failed", `The token could not be decrypted with ${setting}: ${error.message}`, { cause: error });
|
|
723
|
+
throw error;
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
function encryptionKeyFromFile(path, setting = "clientEncryptionKeyPath") {
|
|
728
|
+
let current;
|
|
729
|
+
return async () => {
|
|
730
|
+
const nodeCrypto = await loadNodeCrypto();
|
|
731
|
+
if (!nodeCrypto) throw new AuthioConfigurationError(`${setting} needs Node; pass clientEncryptionKey instead.`);
|
|
732
|
+
const { readFile, stat } = await import('fs/promises');
|
|
733
|
+
let written;
|
|
734
|
+
try {
|
|
735
|
+
written = (await stat(path)).mtimeMs;
|
|
736
|
+
} catch (error) {
|
|
737
|
+
throw new AuthioConfigurationError(`${setting} '${path}' could not be read.`, { cause: error });
|
|
738
|
+
}
|
|
739
|
+
if (!current || current.written !== written) current = { written, key: readFile(path, "utf8") };
|
|
740
|
+
return current.key;
|
|
628
741
|
};
|
|
629
742
|
}
|
|
743
|
+
function algorithmOf(token) {
|
|
744
|
+
try {
|
|
745
|
+
return String(decodeProtectedHeader(token).alg ?? "");
|
|
746
|
+
} catch (error) {
|
|
747
|
+
throw new AuthioTokenValidationError("decryption_failed", "The encrypted token's header could not be read.", { cause: error });
|
|
748
|
+
}
|
|
749
|
+
}
|
|
630
750
|
async function importDecryptionKey(key, algorithm, setting) {
|
|
631
751
|
try {
|
|
632
752
|
if (typeof key !== "string") return await importPrivateJwk(key, algorithm, setting);
|
|
@@ -666,14 +786,295 @@ function toBase64(bytes) {
|
|
|
666
786
|
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
667
787
|
return btoa(binary);
|
|
668
788
|
}
|
|
789
|
+
function createAuthioSigningKeys(connection, discovery) {
|
|
790
|
+
let keys;
|
|
791
|
+
return async (signal) => {
|
|
792
|
+
const document = await discovery.get(signal);
|
|
793
|
+
const uri = document.jwks_uri;
|
|
794
|
+
if (!uri) throw new AuthioError("The Authio discovery document has no jwks_uri.");
|
|
795
|
+
if (!keys || keys.uri !== uri)
|
|
796
|
+
keys = { uri, set: createRemoteJWKSet(new URL(uri), { [customFetch]: connection.fetch, timeoutDuration: connection.httpTimeoutMs }) };
|
|
797
|
+
return keys.set;
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
async function verifyAuthioJwt(token, keys, expected) {
|
|
801
|
+
if (!looksLikeJws(token))
|
|
802
|
+
throw new AuthioTokenValidationError("reference_token", "The token is not a JWT; only introspection can resolve it ('introspectionOnly').");
|
|
803
|
+
try {
|
|
804
|
+
const { payload, protectedHeader } = await jwtVerify(token, keys, {
|
|
805
|
+
issuer: expected.issuer,
|
|
806
|
+
audience: [...expected.audiences],
|
|
807
|
+
algorithms: [...expected.algorithms && expected.algorithms.length > 0 ? expected.algorithms : AuthioAsymmetricAlgorithms],
|
|
808
|
+
clockTolerance: expected.clockSkew ?? AuthioDefaults.ClockSkew,
|
|
809
|
+
requiredClaims: [.../* @__PURE__ */ new Set(["exp", ...expected.requiredClaims ?? []])],
|
|
810
|
+
currentDate: new Date(expected.now)
|
|
811
|
+
});
|
|
812
|
+
return { payload, header: protectedHeader };
|
|
813
|
+
} catch (error) {
|
|
814
|
+
throw toTokenValidationError(error, expected.audiences, token);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
function toTokenValidationError(error, audiences, token) {
|
|
818
|
+
if (error instanceof AuthioTokenValidationError) return error;
|
|
819
|
+
const refuse = (reason, message) => new AuthioTokenValidationError(reason, message, { cause: error });
|
|
820
|
+
if (error instanceof errors.JWTExpired) {
|
|
821
|
+
const exp = error.payload.exp;
|
|
822
|
+
return refuse("expired", typeof exp === "number" ? `The token expired at '${new Date(exp * 1e3).toISOString()}'` : "The token has expired");
|
|
823
|
+
}
|
|
824
|
+
if (error instanceof errors.JWTClaimValidationFailed) {
|
|
825
|
+
switch (error.claim) {
|
|
826
|
+
case "aud":
|
|
827
|
+
return refuse("invalid_audience", describeAudience([error.payload.aud ?? []].flat(), audiences));
|
|
828
|
+
case "iss":
|
|
829
|
+
return refuse("invalid_issuer", `The issuer '${error.payload.iss ?? ""}' is invalid`);
|
|
830
|
+
case "nbf":
|
|
831
|
+
return refuse(
|
|
832
|
+
"not_yet_valid",
|
|
833
|
+
typeof error.payload.nbf === "number" ? `The token is not valid before '${new Date(error.payload.nbf * 1e3).toISOString()}'` : "The token is not valid yet"
|
|
834
|
+
);
|
|
835
|
+
case "exp":
|
|
836
|
+
return refuse("expired", "The token has no expiration");
|
|
837
|
+
default:
|
|
838
|
+
return refuse("malformed", `The token's ${error.claim} claim is invalid`);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
if (error instanceof errors.JWSSignatureVerificationFailed) return refuse("invalid_signature", "The signature is invalid");
|
|
842
|
+
if (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys)
|
|
843
|
+
return refuse("invalid_signature", "The signature key was not found");
|
|
844
|
+
if (error instanceof errors.JOSEAlgNotAllowed) return refuse("invalid_algorithm", `The algorithm '${algorithmOf2(token)}' is not available`);
|
|
845
|
+
if (error instanceof errors.JWKSTimeout || error instanceof errors.JWKSInvalid)
|
|
846
|
+
return refuse("signing_keys_unavailable", "Authio could not be reached to read its signing keys.");
|
|
847
|
+
if (error instanceof errors.JWTInvalid || error instanceof errors.JWSInvalid) return refuse("malformed", "The token is malformed");
|
|
848
|
+
if (error instanceof errors.JOSEError) return refuse("malformed", error.message);
|
|
849
|
+
return refuse("signing_keys_unavailable", "Authio could not be reached to read its signing keys.");
|
|
850
|
+
}
|
|
851
|
+
async function computeAuthioTokenHash(value, algorithm) {
|
|
852
|
+
const size = /(\d{3})$/.exec(algorithm)?.[1];
|
|
853
|
+
const hash = size === "384" ? "SHA-384" : size === "512" ? "SHA-512" : "SHA-256";
|
|
854
|
+
const digest = new Uint8Array(await crypto.subtle.digest(hash, new TextEncoder().encode(value)));
|
|
855
|
+
return toBase64Url(digest.subarray(0, digest.length / 2));
|
|
856
|
+
}
|
|
857
|
+
async function validateAuthioIdToken(token, context, expectations = {}) {
|
|
858
|
+
const signed = isAuthioTokenEncrypted(token) ? await context.decrypt(token) : token;
|
|
859
|
+
const { payload, header } = await verifyAuthioJwt(signed, context.keys, {
|
|
860
|
+
issuer: context.issuer,
|
|
861
|
+
audiences: [context.clientId],
|
|
862
|
+
algorithms: context.algorithms,
|
|
863
|
+
clockSkew: context.clockSkew,
|
|
864
|
+
now: context.now,
|
|
865
|
+
requiredClaims: ["sub", "iat"]
|
|
866
|
+
});
|
|
867
|
+
const type = typeof payload.typ === "string" ? payload.typ : void 0;
|
|
868
|
+
if (type !== void 0 && type.toLowerCase() !== "id")
|
|
869
|
+
throw new AuthioTokenValidationError("not_id_token", `Only ID tokens are accepted; this token's typ is '${type}'.`);
|
|
870
|
+
const audiences = [payload.aud ?? []].flat();
|
|
871
|
+
if (audiences.length > 1 && payload.azp !== context.clientId)
|
|
872
|
+
throw new AuthioTokenValidationError("invalid_audience", `The ID token has several audiences and its azp is not '${context.clientId}'.`);
|
|
873
|
+
if (expectations.nonce !== void 0 && payload[AuthioClaimTypes.Nonce] !== expectations.nonce)
|
|
874
|
+
throw new AuthioTokenValidationError(
|
|
875
|
+
"invalid_nonce",
|
|
876
|
+
payload[AuthioClaimTypes.Nonce] === void 0 ? "The ID token carries no nonce, although one was sent." : "The ID token's nonce is not the one sent."
|
|
877
|
+
);
|
|
878
|
+
const atHash = payload[AuthioClaimTypes.AccessTokenHash];
|
|
879
|
+
if (expectations.accessToken !== void 0 && typeof atHash === "string") {
|
|
880
|
+
const expected = await computeAuthioTokenHash(expectations.accessToken, String(header.alg ?? ""));
|
|
881
|
+
if (expected !== atHash) throw new AuthioTokenValidationError("invalid_at_hash", "The ID token's at_hash does not match the access token.");
|
|
882
|
+
}
|
|
883
|
+
if (expectations.maxAge !== void 0) {
|
|
884
|
+
const authTime = payload[AuthioClaimTypes.AuthTime];
|
|
885
|
+
const skew = context.clockSkew ?? AuthioDefaults.ClockSkew;
|
|
886
|
+
if (typeof authTime !== "number")
|
|
887
|
+
throw new AuthioTokenValidationError("authentication_too_old", "max_age was requested, and the ID token carries no auth_time.");
|
|
888
|
+
if ((authTime + expectations.maxAge + skew) * 1e3 < context.now)
|
|
889
|
+
throw new AuthioTokenValidationError(
|
|
890
|
+
"authentication_too_old",
|
|
891
|
+
`The person signed in at '${new Date(authTime * 1e3).toISOString()}', more than ${expectations.maxAge} seconds ago.`
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
return payload;
|
|
895
|
+
}
|
|
896
|
+
async function validateAuthioLogoutToken(token, context) {
|
|
897
|
+
const signed = isAuthioTokenEncrypted(token) ? await context.decrypt(token) : token;
|
|
898
|
+
const invalid = (message) => new AuthioTokenValidationError("invalid_logout_token", message);
|
|
899
|
+
let headerType;
|
|
900
|
+
try {
|
|
901
|
+
const header = decodeProtectedHeader(signed);
|
|
902
|
+
headerType = typeof header.typ === "string" ? header.typ.toLowerCase() : void 0;
|
|
903
|
+
} catch (error) {
|
|
904
|
+
throw new AuthioTokenValidationError("malformed", "The logout token is malformed", { cause: error });
|
|
905
|
+
}
|
|
906
|
+
const { payload } = await verifyAuthioJwt(signed, context.keys, {
|
|
907
|
+
issuer: context.issuer,
|
|
908
|
+
audiences: [context.clientId],
|
|
909
|
+
algorithms: context.algorithms,
|
|
910
|
+
clockSkew: context.clockSkew,
|
|
911
|
+
now: context.now,
|
|
912
|
+
requiredClaims: ["iat"]
|
|
913
|
+
});
|
|
914
|
+
if (headerType !== AuthioDefaults.LogoutTokenType && headerType !== `application/${AuthioDefaults.LogoutTokenType}`)
|
|
915
|
+
throw invalid(`The token's header typ is '${headerType ?? ""}', not '${AuthioDefaults.LogoutTokenType}'.`);
|
|
916
|
+
const events = payload[AuthioClaimTypes.Events];
|
|
917
|
+
if (!events || typeof events !== "object" || Array.isArray(events) || typeof events[AuthioDefaults.BackchannelLogoutEvent] !== "object")
|
|
918
|
+
throw invalid("The token carries no back-channel logout event.");
|
|
919
|
+
if (payload[AuthioClaimTypes.Nonce] !== void 0) throw invalid("A logout token must not carry a nonce.");
|
|
920
|
+
const subject = typeof payload.sub === "string" && payload.sub ? payload.sub : void 0;
|
|
921
|
+
const sessionId = typeof payload.sid === "string" && payload.sid ? payload.sid : void 0;
|
|
922
|
+
if (!subject && !sessionId) throw invalid("The logout token names neither a subject nor a session.");
|
|
923
|
+
return Object.freeze({ subject, sessionId, tokenId: typeof payload.jti === "string" ? payload.jti : void 0, claims: Object.freeze({ ...payload }) });
|
|
924
|
+
}
|
|
925
|
+
function describeAudience(tokenAudiences, audiences) {
|
|
926
|
+
const known = tokenAudiences.length === 0 ? "" : ` ${tokenAudiences.map((audience) => `'${audience}'`).join(" and ")}`;
|
|
927
|
+
const accepted = audiences.map((audience) => `'${audience}'`).join(" or ");
|
|
928
|
+
return audiences.length === 1 ? `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for that resource (RFC 8707).` : `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for one of those resources (RFC 8707).`;
|
|
929
|
+
}
|
|
930
|
+
function looksLikeJws(token) {
|
|
931
|
+
const parts = token.split(".");
|
|
932
|
+
return parts.length === 3 && parts[0].length > 0;
|
|
933
|
+
}
|
|
934
|
+
function algorithmOf2(token) {
|
|
935
|
+
try {
|
|
936
|
+
return String(decodeProtectedHeader(token).alg ?? "");
|
|
937
|
+
} catch {
|
|
938
|
+
return "";
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function toBase64Url(bytes) {
|
|
942
|
+
let binary = "";
|
|
943
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
944
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// src/authorization.ts
|
|
948
|
+
async function createAuthioPkce(method = "S256") {
|
|
949
|
+
if (method !== "S256" && method !== "plain") throw new TypeError(`The PKCE method '${String(method)}' is not S256 or plain.`);
|
|
950
|
+
const codeVerifier = randomValue(32);
|
|
951
|
+
const codeChallenge = method === "plain" ? codeVerifier : toBase64Url2(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier))));
|
|
952
|
+
return { codeVerifier, codeChallenge, codeChallengeMethod: method };
|
|
953
|
+
}
|
|
954
|
+
function randomValue(bytes = 32) {
|
|
955
|
+
return toBase64Url2(crypto.getRandomValues(new Uint8Array(bytes)));
|
|
956
|
+
}
|
|
957
|
+
async function buildAuthorizationUrl(endpoint, clientId, request) {
|
|
958
|
+
const pkce = await createAuthioPkce(request.codeChallengeMethod ?? "S256");
|
|
959
|
+
const state = request.state?.trim() || randomValue();
|
|
960
|
+
const nonce = request.nonce?.trim() || randomValue();
|
|
961
|
+
if (request.maxAge !== void 0 && (!Number.isInteger(request.maxAge) || request.maxAge < 0))
|
|
962
|
+
throw new RangeError("maxAge must be a non-negative whole number of seconds.");
|
|
963
|
+
const display = request.popup ? "popup" : request.display;
|
|
964
|
+
const responseMode = request.popup ? "web_message" : request.responseMode;
|
|
965
|
+
const url = new URL(endpoint);
|
|
966
|
+
const parameters = {
|
|
967
|
+
...request.extraParameters,
|
|
968
|
+
response_type: "code",
|
|
969
|
+
client_id: clientId,
|
|
970
|
+
redirect_uri: request.redirectUri,
|
|
971
|
+
scope: toScopeString(request.scopes) ?? "openid",
|
|
972
|
+
state,
|
|
973
|
+
nonce,
|
|
974
|
+
code_challenge: pkce.codeChallenge,
|
|
975
|
+
code_challenge_method: pkce.codeChallengeMethod,
|
|
976
|
+
resource: request.resource,
|
|
977
|
+
organization: request.organization,
|
|
978
|
+
prompt: joined(request.prompt),
|
|
979
|
+
max_age: request.maxAge?.toString(),
|
|
980
|
+
acr_values: joined(request.acrValues),
|
|
981
|
+
login_hint: request.loginHint,
|
|
982
|
+
id_token_hint: request.idTokenHint,
|
|
983
|
+
ui_locales: joined(request.uiLocales),
|
|
984
|
+
display,
|
|
985
|
+
response_mode: responseMode,
|
|
986
|
+
idp_hint: request.idpHint
|
|
987
|
+
};
|
|
988
|
+
for (const [name, value] of Object.entries(parameters)) if (value !== void 0 && value !== "") url.searchParams.set(name, value);
|
|
989
|
+
return {
|
|
990
|
+
url: url.toString(),
|
|
991
|
+
transaction: Object.freeze({
|
|
992
|
+
state,
|
|
993
|
+
nonce,
|
|
994
|
+
codeVerifier: pkce.codeVerifier,
|
|
995
|
+
codeChallengeMethod: pkce.codeChallengeMethod,
|
|
996
|
+
redirectUri: request.redirectUri,
|
|
997
|
+
...request.resource ? { resource: request.resource } : {},
|
|
998
|
+
...request.maxAge !== void 0 ? { maxAge: request.maxAge } : {}
|
|
999
|
+
})
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
function readCallbackParameters(callback) {
|
|
1003
|
+
if (callback instanceof URLSearchParams) return Object.fromEntries(callback);
|
|
1004
|
+
if (callback instanceof URL) return Object.fromEntries(callback.searchParams);
|
|
1005
|
+
if (typeof callback === "string") {
|
|
1006
|
+
const text = callback.trim();
|
|
1007
|
+
const query = /^[a-z][a-z0-9+.-]*:/i.test(text) ? new URL(text).search : text.slice(text.indexOf("?") + 1);
|
|
1008
|
+
return Object.fromEntries(new URLSearchParams(query));
|
|
1009
|
+
}
|
|
1010
|
+
const parameters = {};
|
|
1011
|
+
for (const [name, value] of Object.entries(callback ?? {})) {
|
|
1012
|
+
const first = Array.isArray(value) ? value[0] : value;
|
|
1013
|
+
if (typeof first === "string") parameters[name] = first;
|
|
1014
|
+
}
|
|
1015
|
+
return parameters;
|
|
1016
|
+
}
|
|
1017
|
+
function parseAuthioBearerChallenge(header) {
|
|
1018
|
+
if (!header || !/^\s*bearer(\s|$)/i.test(header)) return void 0;
|
|
1019
|
+
const values = {};
|
|
1020
|
+
for (const match of header.matchAll(/([a-zA-Z_]+)\s*=\s*"((?:[^"\\]|\\.)*)"|([a-zA-Z_]+)\s*=\s*([^,\s]+)/g)) {
|
|
1021
|
+
const name = (match[1] ?? match[3] ?? "").toLowerCase();
|
|
1022
|
+
values[name] ??= (match[2] ?? match[4] ?? "").replace(/\\(.)/g, "$1");
|
|
1023
|
+
}
|
|
1024
|
+
const maxAge = values.max_age !== void 0 && /^\d+$/.test(values.max_age) ? Number(values.max_age) : void 0;
|
|
1025
|
+
return {
|
|
1026
|
+
error: values.error,
|
|
1027
|
+
errorDescription: values.error_description,
|
|
1028
|
+
scope: values.scope,
|
|
1029
|
+
acrValues: values.acr_values,
|
|
1030
|
+
maxAge,
|
|
1031
|
+
resourceMetadata: values.resource_metadata
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
function joined(value) {
|
|
1035
|
+
if (value === void 0) return void 0;
|
|
1036
|
+
const text = (typeof value === "string" ? [value] : [...value]).map((item) => item.trim()).filter(Boolean).join(" ");
|
|
1037
|
+
return text || void 0;
|
|
1038
|
+
}
|
|
1039
|
+
function toBase64Url2(bytes) {
|
|
1040
|
+
let binary = "";
|
|
1041
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1042
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// src/client.ts
|
|
669
1046
|
function createAuthioClient(options) {
|
|
670
1047
|
const connection = resolveConnection(options);
|
|
671
1048
|
const discovery = createAuthioDiscoveryClient(connection);
|
|
672
1049
|
const authenticator = createClientAuthenticator(options, connection);
|
|
673
1050
|
const refreshSkewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, "tokenRefreshSkew");
|
|
674
|
-
const
|
|
1051
|
+
const clockSkew = seconds(options.clockSkew, AuthioDefaults.ClockSkew, "clockSkew") / 1e3;
|
|
1052
|
+
const decrypt = createAuthioTokenDecrypter(resolveEncryptionKey(options), {
|
|
1053
|
+
setting: options.clientEncryptionKey === void 0 && options.clientEncryptionKeyPath ? "clientEncryptionKeyPath" : "clientEncryptionKey",
|
|
1054
|
+
allowLegacyEncryptionAlgorithms: options.allowLegacyEncryptionAlgorithms
|
|
1055
|
+
});
|
|
1056
|
+
const signingKeys = createAuthioSigningKeys(connection, discovery);
|
|
675
1057
|
const tokens = createTokenClient(connection, discovery, authenticator);
|
|
676
1058
|
const clientCredentials = createClientCredentialsCache(connection, authenticator.clientId, tokens, refreshSkewMs);
|
|
1059
|
+
const validationContext = async (signal) => ({
|
|
1060
|
+
keys: await signingKeys(signal),
|
|
1061
|
+
decrypt,
|
|
1062
|
+
issuer: connection.issuer,
|
|
1063
|
+
clientId: authenticator.clientId,
|
|
1064
|
+
algorithms: options.validAlgorithms,
|
|
1065
|
+
clockSkew,
|
|
1066
|
+
now: connection.clock.now()
|
|
1067
|
+
});
|
|
1068
|
+
const validateIdToken = async (idToken, expectations = {}) => {
|
|
1069
|
+
requireValue(idToken, "idToken");
|
|
1070
|
+
return validateAuthioIdToken(idToken, await validationContext(expectations.signal), expectations);
|
|
1071
|
+
};
|
|
1072
|
+
const createAuthorizationUrl = async (request = {}) => {
|
|
1073
|
+
const redirectUri = request.redirectUri ?? options.redirectUri;
|
|
1074
|
+
requireValue(redirectUri, "redirectUri");
|
|
1075
|
+
const document = await discovery.get(request.signal);
|
|
1076
|
+
return buildAuthorizationUrl(requireEndpoint(document, "authorization_endpoint"), authenticator.clientId, { ...request, redirectUri });
|
|
1077
|
+
};
|
|
677
1078
|
return {
|
|
678
1079
|
issuer: connection.issuer,
|
|
679
1080
|
clientId: authenticator.clientId,
|
|
@@ -716,7 +1117,12 @@ function createAuthioClient(options) {
|
|
|
716
1117
|
);
|
|
717
1118
|
const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
718
1119
|
if (response.ok && mediaType === "application/jwt")
|
|
719
|
-
return readUserInfoJwt((await response.text()).trim(), document, connection, authenticator.clientId, decrypt,
|
|
1120
|
+
return readUserInfoJwt((await response.text()).trim(), document, connection, authenticator.clientId, decrypt, signingKeys, {
|
|
1121
|
+
algorithms: options.validAlgorithms,
|
|
1122
|
+
clockSkew,
|
|
1123
|
+
status: response.status,
|
|
1124
|
+
signal: callOptions.signal
|
|
1125
|
+
});
|
|
720
1126
|
if (!response.ok) {
|
|
721
1127
|
const body = await response.text();
|
|
722
1128
|
const challenge = toErrorResponse(body) ? void 0 : readBearerChallenge(response);
|
|
@@ -724,6 +1130,66 @@ function createAuthioClient(options) {
|
|
|
724
1130
|
}
|
|
725
1131
|
return readProtocolJson(response);
|
|
726
1132
|
},
|
|
1133
|
+
createAuthorizationUrl,
|
|
1134
|
+
async handleAuthorizationCallback(callback, transaction, callOptions = {}) {
|
|
1135
|
+
if (!transaction?.state || !transaction.redirectUri) throw new TypeError("transaction is required: keep what createAuthorizationUrl returned.");
|
|
1136
|
+
const parameters = readCallbackParameters(callback);
|
|
1137
|
+
if (parameters.state !== transaction.state)
|
|
1138
|
+
throw new AuthioCallbackError("state_mismatch", "The callback's state is not the one this sign-in was started with.");
|
|
1139
|
+
const document = await discovery.get(callOptions.signal);
|
|
1140
|
+
if (parameters.iss !== void 0) {
|
|
1141
|
+
if (parameters.iss.replace(/\/+$/, "") !== connection.issuer)
|
|
1142
|
+
throw new AuthioCallbackError("issuer_mismatch", `The callback comes from the issuer '${parameters.iss}', not '${connection.issuer}' (RFC 9207).`);
|
|
1143
|
+
} else if (document.authorization_response_iss_parameter_supported === true) {
|
|
1144
|
+
throw new AuthioCallbackError("missing_issuer", "The callback carries no iss parameter, although Authio sends one (RFC 9207).");
|
|
1145
|
+
}
|
|
1146
|
+
if (parameters.error) throw new AuthioProtocolError(parameters.error, parameters.error_description, parameters.error_code);
|
|
1147
|
+
if (!parameters.code) throw new AuthioCallbackError("missing_code", "The callback carries neither a code nor an error.");
|
|
1148
|
+
const answer = await tokens.authorizationCode({
|
|
1149
|
+
code: parameters.code,
|
|
1150
|
+
redirectUri: transaction.redirectUri,
|
|
1151
|
+
codeVerifier: transaction.codeVerifier,
|
|
1152
|
+
resource: transaction.resource,
|
|
1153
|
+
signal: callOptions.signal
|
|
1154
|
+
});
|
|
1155
|
+
const idToken = answer.id_token ? await validateIdToken(answer.id_token, {
|
|
1156
|
+
nonce: transaction.nonce,
|
|
1157
|
+
accessToken: answer.access_token,
|
|
1158
|
+
maxAge: transaction.maxAge,
|
|
1159
|
+
signal: callOptions.signal
|
|
1160
|
+
}) : void 0;
|
|
1161
|
+
return { tokens: answer, idToken };
|
|
1162
|
+
},
|
|
1163
|
+
validateIdToken,
|
|
1164
|
+
async validateLogoutToken(logoutToken, callOptions = {}) {
|
|
1165
|
+
requireValue(logoutToken, "logoutToken");
|
|
1166
|
+
return validateAuthioLogoutToken(logoutToken, await validationContext(callOptions.signal));
|
|
1167
|
+
},
|
|
1168
|
+
async createEndSessionUrl(request = {}) {
|
|
1169
|
+
const document = await discovery.get(request.signal);
|
|
1170
|
+
const url = new URL(requireEndpoint(document, "end_session_endpoint"));
|
|
1171
|
+
const locales = request.uiLocales === void 0 ? void 0 : (typeof request.uiLocales === "string" ? [request.uiLocales] : [...request.uiLocales]).join(" ");
|
|
1172
|
+
const parameters = {
|
|
1173
|
+
id_token_hint: request.idTokenHint,
|
|
1174
|
+
post_logout_redirect_uri: request.postLogoutRedirectUri ?? options.postLogoutRedirectUri,
|
|
1175
|
+
state: request.state,
|
|
1176
|
+
ui_locales: locales,
|
|
1177
|
+
client_id: request.includeClientId === false ? void 0 : authenticator.clientId
|
|
1178
|
+
};
|
|
1179
|
+
for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);
|
|
1180
|
+
return url.toString();
|
|
1181
|
+
},
|
|
1182
|
+
async createStepUpAuthorizationUrl(challenge, request = {}) {
|
|
1183
|
+
const parsed = typeof challenge === "string" ? parseAuthioBearerChallenge(challenge) : challenge;
|
|
1184
|
+
if (!parsed || parsed.error !== AuthioOAuthErrors.InsufficientUserAuthentication)
|
|
1185
|
+
throw new TypeError("The challenge is not an insufficient_user_authentication bearer challenge.");
|
|
1186
|
+
return createAuthorizationUrl({
|
|
1187
|
+
...request,
|
|
1188
|
+
acrValues: request.acrValues ?? parsed.acrValues,
|
|
1189
|
+
maxAge: request.maxAge ?? parsed.maxAge,
|
|
1190
|
+
prompt: request.prompt ?? (parsed.maxAge === 0 ? "login" : void 0)
|
|
1191
|
+
});
|
|
1192
|
+
},
|
|
727
1193
|
clientCredentialsFetch(fetchOptions = {}) {
|
|
728
1194
|
const inner = fetchOptions.fetch ?? connection.fetch;
|
|
729
1195
|
const key = { scopes: fetchOptions.scopes, resource: fetchOptions.resource };
|
|
@@ -745,8 +1211,8 @@ function createAuthioClient(options) {
|
|
|
745
1211
|
};
|
|
746
1212
|
}
|
|
747
1213
|
function createTokenClient(connection, discovery, authenticator) {
|
|
748
|
-
const requestToken = async (parameters, signal) => {
|
|
749
|
-
const response = await postForm(connection, discovery, authenticator, "token_endpoint", parameters, signal);
|
|
1214
|
+
const requestToken = async (parameters, signal, authenticate = true) => {
|
|
1215
|
+
const response = await postForm(connection, discovery, authenticate ? authenticator : void 0, "token_endpoint", parameters, signal);
|
|
750
1216
|
const token = await readProtocolJson(response);
|
|
751
1217
|
return redact(token, ["access_token", "refresh_token", "id_token"]);
|
|
752
1218
|
};
|
|
@@ -762,12 +1228,9 @@ function createTokenClient(connection, discovery, authenticator) {
|
|
|
762
1228
|
return await requestToken({ grant_type: AuthioGrantTypes.DeviceCode, device_code: authorization.device_code }, options.signal);
|
|
763
1229
|
} catch (error) {
|
|
764
1230
|
if (!(error instanceof AuthioProtocolError)) throw error;
|
|
765
|
-
|
|
766
|
-
if (
|
|
767
|
-
|
|
768
|
-
continue;
|
|
769
|
-
}
|
|
770
|
-
throw error;
|
|
1231
|
+
const outcome = toDevicePollOutcome(error.error);
|
|
1232
|
+
if (outcome.outcome === "failed") throw error;
|
|
1233
|
+
wait += outcome.intervalIncrease * 1e3;
|
|
771
1234
|
}
|
|
772
1235
|
}
|
|
773
1236
|
};
|
|
@@ -843,6 +1306,20 @@ function createTokenClient(connection, discovery, authenticator) {
|
|
|
843
1306
|
return redact(await readProtocolJson(response), ["device_code"]);
|
|
844
1307
|
},
|
|
845
1308
|
pollDevice,
|
|
1309
|
+
personalAccessToken: (options) => {
|
|
1310
|
+
requireValue(options?.token, "token");
|
|
1311
|
+
return requestToken(
|
|
1312
|
+
{
|
|
1313
|
+
grant_type: AuthioGrantTypes.PersonalAccessToken,
|
|
1314
|
+
client_secret: options.token,
|
|
1315
|
+
client_id: options.clientId,
|
|
1316
|
+
scope: toScopeString(options.scopes),
|
|
1317
|
+
resource: options.resource
|
|
1318
|
+
},
|
|
1319
|
+
options.signal,
|
|
1320
|
+
false
|
|
1321
|
+
);
|
|
1322
|
+
},
|
|
846
1323
|
password: (options) => {
|
|
847
1324
|
requireValue(options?.username, "username");
|
|
848
1325
|
if (typeof options.password !== "string") throw new TypeError("password is required.");
|
|
@@ -900,48 +1377,90 @@ function toConnectionExchangeResult(body, status, provider) {
|
|
|
900
1377
|
const token = parseProtocolJson(body, status);
|
|
901
1378
|
if (typeof token.access_token === "string" && token.access_token)
|
|
902
1379
|
return redact(
|
|
903
|
-
{
|
|
1380
|
+
withoutUndefined({
|
|
904
1381
|
status: "granted",
|
|
905
1382
|
accessToken: token.access_token,
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
},
|
|
1383
|
+
issuedTokenType: textOf(token.issued_token_type),
|
|
1384
|
+
tokenType: textOf(token.token_type),
|
|
1385
|
+
expiresIn: typeof token.expires_in === "number" ? token.expires_in : void 0,
|
|
1386
|
+
scope: textOf(token.scope),
|
|
1387
|
+
connectionId: textOf(token.connection_id),
|
|
1388
|
+
provider: textOf(token.provider) ?? provider,
|
|
1389
|
+
providerType: textOf(token.provider_type),
|
|
1390
|
+
externalAccount: token.external_account && typeof token.external_account === "object" ? token.external_account : void 0
|
|
1391
|
+
}),
|
|
915
1392
|
["accessToken"]
|
|
916
1393
|
);
|
|
917
1394
|
}
|
|
918
1395
|
const error = toErrorResponse(body);
|
|
919
|
-
const
|
|
1396
|
+
const errorDescription = error?.error_description?.trim() ? error.error_description : `Authio answered HTTP ${status} to the connected-account token exchange.`;
|
|
1397
|
+
const errorCode = textOf(error?.error_code);
|
|
920
1398
|
switch (error?.error) {
|
|
921
1399
|
case AuthioOAuthErrors.ConnectionRequired:
|
|
922
|
-
return {
|
|
1400
|
+
return withoutUndefined({
|
|
1401
|
+
status: "required",
|
|
1402
|
+
connectUri: textOf(error.connect_uri),
|
|
1403
|
+
provider: textOf(error.connection_provider) ?? provider,
|
|
1404
|
+
errorCode,
|
|
1405
|
+
errorDescription
|
|
1406
|
+
});
|
|
923
1407
|
case AuthioOAuthErrors.ConnectionSelectionRequired:
|
|
924
|
-
return {
|
|
1408
|
+
return withoutUndefined({
|
|
1409
|
+
status: "selection_required",
|
|
1410
|
+
provider: textOf(error.connection_provider) ?? provider,
|
|
1411
|
+
connections: (Array.isArray(error.connections) ? error.connections : []).map(toConnectionChoice),
|
|
1412
|
+
errorCode,
|
|
1413
|
+
errorDescription
|
|
1414
|
+
});
|
|
925
1415
|
default:
|
|
926
|
-
return {
|
|
1416
|
+
return withoutUndefined({
|
|
1417
|
+
status: "refused",
|
|
1418
|
+
error: error?.error ?? `http_${status}`,
|
|
1419
|
+
errorCode,
|
|
1420
|
+
errorDescription,
|
|
1421
|
+
connectUri: textOf(error?.connect_uri)
|
|
1422
|
+
});
|
|
927
1423
|
}
|
|
928
1424
|
}
|
|
1425
|
+
function toDevicePollOutcome(error) {
|
|
1426
|
+
if (error === AuthioOAuthErrors.AuthorizationPending) return { outcome: "keep_polling", intervalIncrease: 0 };
|
|
1427
|
+
if (error === AuthioOAuthErrors.SlowDown) return { outcome: "keep_polling", intervalIncrease: AuthioDefaults.DeviceSlowDownIncrement };
|
|
1428
|
+
return { outcome: "failed", error };
|
|
1429
|
+
}
|
|
1430
|
+
function toConnectionChoice(value) {
|
|
1431
|
+
const record = value && typeof value === "object" ? value : {};
|
|
1432
|
+
return withoutUndefined({ id: textOf(record.id) ?? "", label: textOf(record.label), externalLogin: textOf(record.external_login) });
|
|
1433
|
+
}
|
|
1434
|
+
function textOf(value) {
|
|
1435
|
+
return typeof value === "string" && value ? value : void 0;
|
|
1436
|
+
}
|
|
1437
|
+
function withoutUndefined(value) {
|
|
1438
|
+
for (const key of Object.keys(value)) if (value[key] === void 0) delete value[key];
|
|
1439
|
+
return value;
|
|
1440
|
+
}
|
|
1441
|
+
function resolveEncryptionKey(options) {
|
|
1442
|
+
if (options.clientEncryptionKey !== void 0) return options.clientEncryptionKey;
|
|
1443
|
+
if (options.clientEncryptionKeyPath) return encryptionKeyFromFile(options.clientEncryptionKeyPath);
|
|
1444
|
+
return void 0;
|
|
1445
|
+
}
|
|
929
1446
|
async function postForm(connection, discovery, authenticator, endpoint, parameters, signal) {
|
|
930
1447
|
const document = await discovery.get(signal);
|
|
931
1448
|
const url = requireEndpoint(document, endpoint);
|
|
932
1449
|
const form = formBody(parameters);
|
|
933
1450
|
const headers = new Headers({ accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
|
|
934
|
-
await authenticator
|
|
1451
|
+
await authenticator?.apply(form, headers);
|
|
935
1452
|
return send(connection, url, { method: "POST", headers, body: form.toString() }, signal);
|
|
936
1453
|
}
|
|
937
|
-
async function readUserInfoJwt(jwt, document, connection, clientId, decrypt,
|
|
1454
|
+
async function readUserInfoJwt(jwt, document, connection, clientId, decrypt, signingKeys, settings) {
|
|
938
1455
|
try {
|
|
939
1456
|
const signed = isAuthioTokenEncrypted(jwt) ? await decrypt(jwt) : jwt;
|
|
940
|
-
const
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
1457
|
+
const { payload } = await verifyAuthioJwt(signed, await signingKeys(settings.signal), {
|
|
1458
|
+
issuer: document.issuer.replace(/\/+$/, ""),
|
|
1459
|
+
audiences: [clientId],
|
|
1460
|
+
algorithms: settings.algorithms,
|
|
1461
|
+
clockSkew: settings.clockSkew,
|
|
1462
|
+
now: connection.clock.now(),
|
|
1463
|
+
requiredClaims: ["sub"]
|
|
945
1464
|
});
|
|
946
1465
|
return payload;
|
|
947
1466
|
} catch (error) {
|
|
@@ -949,7 +1468,7 @@ async function readUserInfoJwt(jwt, document, connection, clientId, decrypt, sta
|
|
|
949
1468
|
"invalid_userinfo",
|
|
950
1469
|
`The userinfo JWT could not be verified: ${error?.message ?? "unknown reason."}`,
|
|
951
1470
|
void 0,
|
|
952
|
-
status,
|
|
1471
|
+
settings.status,
|
|
953
1472
|
{ cause: error }
|
|
954
1473
|
);
|
|
955
1474
|
}
|
|
@@ -971,6 +1490,149 @@ function requireValue(value, name) {
|
|
|
971
1490
|
if (typeof value !== "string" || !value.trim()) throw new TypeError(`${name} is required.`);
|
|
972
1491
|
}
|
|
973
1492
|
|
|
1493
|
+
// src/admin.ts
|
|
1494
|
+
function parseAuthioAdminEnvelope(status, body, headers) {
|
|
1495
|
+
const parsed = parseJson(body);
|
|
1496
|
+
if (status >= 200 && status < 300) {
|
|
1497
|
+
if (!parsed) return { ok: true };
|
|
1498
|
+
return withoutUndefined2({ ok: true, data: parsed.data });
|
|
1499
|
+
}
|
|
1500
|
+
const notifications = Array.isArray(parsed?.notifications) ? parsed.notifications.map(toNotification).filter((item) => item.message) : [];
|
|
1501
|
+
return {
|
|
1502
|
+
ok: false,
|
|
1503
|
+
error: new AuthioAdminError({
|
|
1504
|
+
status,
|
|
1505
|
+
errorCode: textOf2(parsed?.errorCode),
|
|
1506
|
+
notifications,
|
|
1507
|
+
requestId: textOf2(parsed?.requestId) ?? headerOf(headers, AuthioDefaults.RequestIdHeader),
|
|
1508
|
+
retryAfterSeconds: retryAfterOf(headerOf(headers, "Retry-After"))
|
|
1509
|
+
})
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
async function readAuthioAdminResponse(response) {
|
|
1513
|
+
const envelope = parseAuthioAdminEnvelope(response.status, response.status === 204 ? null : await response.text(), response.headers);
|
|
1514
|
+
if (!envelope.ok) throw envelope.error;
|
|
1515
|
+
return envelope;
|
|
1516
|
+
}
|
|
1517
|
+
function createAuthioAccountCredential(options) {
|
|
1518
|
+
const value = options.credential?.trim();
|
|
1519
|
+
if (!value) throw new AuthioConfigurationError("The account credential is required.");
|
|
1520
|
+
const kind = value.startsWith(AuthioDefaults.ApiKeyPrefix) ? "api_key" : value.startsWith(AuthioDefaults.ClientSecretPrefix) ? "client_secret" : value.startsWith(AuthioDefaults.PersonalAccessTokenPrefix) ? "personal_access_token" : void 0;
|
|
1521
|
+
if (!kind)
|
|
1522
|
+
throw new AuthioConfigurationError(
|
|
1523
|
+
`The account credential must start with ${AuthioDefaults.ApiKeyPrefix}, ${AuthioDefaults.ClientSecretPrefix} or ${AuthioDefaults.PersonalAccessTokenPrefix}.`
|
|
1524
|
+
);
|
|
1525
|
+
const exchanged = kind === "client_secret" || kind === "personal_access_token" && options.exchangePersonalAccessToken === true;
|
|
1526
|
+
const clock = options.clock ?? systemClock;
|
|
1527
|
+
const inner = options.fetch ?? globalThis.fetch;
|
|
1528
|
+
const scope = toScopeString(options.scopes);
|
|
1529
|
+
const refreshSkewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, "tokenRefreshSkew");
|
|
1530
|
+
let client;
|
|
1531
|
+
let cached;
|
|
1532
|
+
let pending;
|
|
1533
|
+
if (exchanged) {
|
|
1534
|
+
if (kind === "client_secret" && !options.credentialId?.trim())
|
|
1535
|
+
throw new AuthioConfigurationError("A cs_ client secret is exchanged with its credential id: set credentialId.");
|
|
1536
|
+
client = createAuthioClient({
|
|
1537
|
+
...options,
|
|
1538
|
+
realm: AuthioDefaults.PlatformRealm,
|
|
1539
|
+
clientId: kind === "client_secret" ? toCredentialClientId(options.credentialId) : AuthioDefaults.PlatformClientId,
|
|
1540
|
+
clientSecret: kind === "client_secret" ? value : void 0,
|
|
1541
|
+
clientAuthentication: kind === "client_secret" ? "client_secret_post" : "none"
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
const exchange = async (signal) => {
|
|
1545
|
+
if (cached && clock.now() < cached.refreshAt) return cached;
|
|
1546
|
+
pending ??= (async () => {
|
|
1547
|
+
const issuedAt = clock.now();
|
|
1548
|
+
const answer = kind === "client_secret" ? await client.tokens.clientCredentials({ scopes: scope, signal }) : await client.tokens.personalAccessToken({ token: value, scopes: scope, signal });
|
|
1549
|
+
cached = toClientCredentialsToken(answer, issuedAt, refreshSkewMs);
|
|
1550
|
+
return cached;
|
|
1551
|
+
})().finally(() => {
|
|
1552
|
+
pending = void 0;
|
|
1553
|
+
});
|
|
1554
|
+
return pending;
|
|
1555
|
+
};
|
|
1556
|
+
const headers = async (signal) => {
|
|
1557
|
+
if (exchanged) {
|
|
1558
|
+
const token = await exchange(signal);
|
|
1559
|
+
return { authorization: `${token.tokenType} ${token.accessToken}` };
|
|
1560
|
+
}
|
|
1561
|
+
return options.presentAs === "x-api-key" ? { [AuthioDefaults.ApiKeyHeader]: value } : { authorization: `Bearer ${value}` };
|
|
1562
|
+
};
|
|
1563
|
+
const authenticatedFetch = async (input, init) => {
|
|
1564
|
+
const request = new Request(input, init);
|
|
1565
|
+
const body = request.body ? await request.arrayBuffer() : void 0;
|
|
1566
|
+
const idempotent = ["GET", "HEAD", "PUT", "DELETE"].includes(request.method.toUpperCase());
|
|
1567
|
+
const attempt = async () => {
|
|
1568
|
+
const merged = new Headers(request.headers);
|
|
1569
|
+
for (const [name, header] of Object.entries(await headers(request.signal))) merged.set(name, header);
|
|
1570
|
+
return inner(request.url, { method: request.method, headers: merged, body, signal: request.signal, redirect: request.redirect });
|
|
1571
|
+
};
|
|
1572
|
+
let response = await attempt();
|
|
1573
|
+
if (response.status === 401 && exchanged) {
|
|
1574
|
+
cached = void 0;
|
|
1575
|
+
response = await attempt();
|
|
1576
|
+
}
|
|
1577
|
+
if ((response.status === 429 || response.status === 503) && idempotent) {
|
|
1578
|
+
const wait = retryAfterOf(response.headers.get("retry-after") ?? void 0);
|
|
1579
|
+
if (wait !== void 0) {
|
|
1580
|
+
await clock.sleep(wait * 1e3, request.signal);
|
|
1581
|
+
response = await attempt();
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
return response;
|
|
1585
|
+
};
|
|
1586
|
+
return {
|
|
1587
|
+
kind,
|
|
1588
|
+
exchanged,
|
|
1589
|
+
headers,
|
|
1590
|
+
invalidate() {
|
|
1591
|
+
cached = void 0;
|
|
1592
|
+
},
|
|
1593
|
+
fetch: authenticatedFetch
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
function toCredentialClientId(credentialId) {
|
|
1597
|
+
const id = credentialId.trim();
|
|
1598
|
+
return id.startsWith(AuthioDefaults.CredentialClientIdPrefix) ? id : `${AuthioDefaults.CredentialClientIdPrefix}${id.replace(/[{}-]/g, "").toLowerCase()}`;
|
|
1599
|
+
}
|
|
1600
|
+
function parseJson(body) {
|
|
1601
|
+
if (!body?.trim()) return void 0;
|
|
1602
|
+
try {
|
|
1603
|
+
return asRecord(JSON.parse(body));
|
|
1604
|
+
} catch {
|
|
1605
|
+
return void 0;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
function asRecord(value) {
|
|
1609
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1610
|
+
}
|
|
1611
|
+
function toNotification(value) {
|
|
1612
|
+
const record = asRecord(value) ?? {};
|
|
1613
|
+
return withoutUndefined2({ message: textOf2(record.message) ?? "", field: textOf2(record.field), code: textOf2(record.code) });
|
|
1614
|
+
}
|
|
1615
|
+
function headerOf(headers, name) {
|
|
1616
|
+
if (!headers) return void 0;
|
|
1617
|
+
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
1618
|
+
const wanted = name.toLowerCase();
|
|
1619
|
+
for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === wanted) return value;
|
|
1620
|
+
return void 0;
|
|
1621
|
+
}
|
|
1622
|
+
function retryAfterOf(value) {
|
|
1623
|
+
if (!value?.trim()) return void 0;
|
|
1624
|
+
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
1625
|
+
const date = Date.parse(value);
|
|
1626
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
1627
|
+
}
|
|
1628
|
+
function textOf2(value) {
|
|
1629
|
+
return typeof value === "string" && value ? value : void 0;
|
|
1630
|
+
}
|
|
1631
|
+
function withoutUndefined2(value) {
|
|
1632
|
+
for (const key of Object.keys(value)) if (value[key] === void 0) delete value[key];
|
|
1633
|
+
return value;
|
|
1634
|
+
}
|
|
1635
|
+
|
|
974
1636
|
// src/resource-access.ts
|
|
975
1637
|
var claimSources = new Map(Object.entries(AuthioResourceAccessClaims).map(([name, source]) => [name.toLowerCase(), source]));
|
|
976
1638
|
var AuthioResourceAccess = class _AuthioResourceAccess {
|
|
@@ -1050,7 +1712,7 @@ function parseResourceAccess(claims) {
|
|
|
1050
1712
|
return roles.length === 0 ? AuthioResourceAccess.empty : new AuthioResourceAccess(roles);
|
|
1051
1713
|
}
|
|
1052
1714
|
function parseResourceAccessClaim(source, value) {
|
|
1053
|
-
const root = typeof value === "string" ?
|
|
1715
|
+
const root = typeof value === "string" ? parseJson2(value) : value;
|
|
1054
1716
|
if (!isPlainObject(root)) return [];
|
|
1055
1717
|
const roles = [];
|
|
1056
1718
|
for (const [name, rolePermissions] of Object.entries(root)) {
|
|
@@ -1107,7 +1769,7 @@ function distinctIgnoringCase(values) {
|
|
|
1107
1769
|
return true;
|
|
1108
1770
|
});
|
|
1109
1771
|
}
|
|
1110
|
-
function
|
|
1772
|
+
function parseJson2(text) {
|
|
1111
1773
|
if (!text.trim()) return void 0;
|
|
1112
1774
|
try {
|
|
1113
1775
|
return JSON.parse(text);
|
|
@@ -1194,9 +1856,23 @@ var asAdminResourceEvent = (event) => dataWhen(
|
|
|
1194
1856
|
AuthioWebhookEventTypes.AdminResourceDeleted
|
|
1195
1857
|
);
|
|
1196
1858
|
var asUserSuspensionEvent = (event) => dataWhen(event, AuthioWebhookEventTypes.UserSuspended, AuthioWebhookEventTypes.UserSuspensionEnded);
|
|
1859
|
+
var asAttackDetectedEvent = (event) => dataWhen(event, AuthioWebhookEventTypes.AttackDetected);
|
|
1860
|
+
var asCredentialCompromisedEvent = (event) => dataWhen(event, AuthioWebhookEventTypes.CredentialCompromised);
|
|
1197
1861
|
var asPingEvent = (event) => dataWhen(event, AuthioWebhookEventTypes.Ping);
|
|
1862
|
+
var knownEventTypes = new Set(Object.values(AuthioWebhookEventTypes));
|
|
1863
|
+
function isKnownWebhookEventType(type) {
|
|
1864
|
+
return knownEventTypes.has(type);
|
|
1865
|
+
}
|
|
1866
|
+
function readWebhookEventData(event) {
|
|
1867
|
+
return isKnownWebhookEventType(event.type) ? dataWhen(event, event.type) : void 0;
|
|
1868
|
+
}
|
|
1869
|
+
function toCamelCasedMembers(value) {
|
|
1870
|
+
const result = {};
|
|
1871
|
+
for (const [name, member] of Object.entries(value)) result[name.replace(/_([a-z0-9])/g, (_, letter) => letter.toUpperCase())] = member;
|
|
1872
|
+
return result;
|
|
1873
|
+
}
|
|
1198
1874
|
function dataWhen(event, ...types) {
|
|
1199
|
-
return types.includes(event.type) && event.data !== null && event.data
|
|
1875
|
+
return types.includes(event.type) && event.data !== null && typeof event.data === "object" && !Array.isArray(event.data) ? toCamelCasedMembers(event.data) : void 0;
|
|
1200
1876
|
}
|
|
1201
1877
|
function parseSignatureHeader(header) {
|
|
1202
1878
|
let timestamp = 0;
|
|
@@ -1235,6 +1911,6 @@ function constantTimeEquals(left, right) {
|
|
|
1235
1911
|
return difference === 0;
|
|
1236
1912
|
}
|
|
1237
1913
|
|
|
1238
|
-
export { AuthioAsymmetricAlgorithms, AuthioClaimTypes, AuthioClientAssertionAlgorithms, AuthioConfigurationError, AuthioContentEncryptionAlgorithms, AuthioDefaults, AuthioDiscoveryError, AuthioError, AuthioGrantTypes, AuthioKeyManagementAlgorithms, AuthioOAuthErrors, AuthioProtocolError, AuthioResourceAccess, AuthioResourceAccessClaims, AuthioScopes, AuthioTokenTypes, AuthioWebhookEventTypes, AuthioWebhookHeaders, asAdminResourceEvent, asKeysRotatedEvent, asLoginEvent, asPingEvent, asTokenReuseDetectedEvent, asTokenRevokedEvent, asUserEvent, asUserLockedOutEvent, asUserSuspensionEvent, computeWebhookSignatureHeader, createAuthioClient, createAuthioDiscoveryClient, createAuthioTokenDecrypter, escapeDataString, isAllowedUrl, isAuthioTokenEncrypted, isWebhookEventOfType, parseResourceAccess, parseResourceAccessClaim, parseWebhookEvent, resolveConnection, resolveIssuer, resourceAccessSourceOf, seconds, systemClock, toBasicAuthorization, toClientCredentialsToken, toScopeString, tryParseWebhookEvent, verifyWebhookSignature };
|
|
1914
|
+
export { AuthioAdminError, AuthioAsymmetricAlgorithms, AuthioCallbackError, AuthioCallerKinds, AuthioClaimTypes, AuthioClientAssertionAlgorithms, AuthioConfigurationError, AuthioContentEncryptionAlgorithms, AuthioDefaults, AuthioDiscoveryError, AuthioError, AuthioGrantTypes, AuthioKeyManagementAlgorithms, AuthioLegacyKeyManagementAlgorithms, AuthioOAuthErrors, AuthioPrompts, AuthioProtocolError, AuthioResourceAccess, AuthioResourceAccessClaims, AuthioScopes, AuthioTokenTypes, AuthioTokenValidationError, AuthioWebhookEventTypes, AuthioWebhookHeaders, asAdminResourceEvent, asAttackDetectedEvent, asCredentialCompromisedEvent, asKeysRotatedEvent, asLoginEvent, asPingEvent, asTokenReuseDetectedEvent, asTokenRevokedEvent, asUserEvent, asUserLockedOutEvent, asUserSuspensionEvent, computeAuthioTokenHash, computeWebhookSignatureHeader, createAuthioAccountCredential, createAuthioClient, createAuthioDiscoveryClient, createAuthioPkce, createAuthioSigningKeys, createAuthioTokenDecrypter, encryptionKeyFromFile, escapeDataString, isAllowedUrl, isAuthioTokenEncrypted, isKnownWebhookEventType, isWebhookEventOfType, parseAuthioAdminEnvelope, parseAuthioBearerChallenge, parseResourceAccess, parseResourceAccessClaim, parseWebhookEvent, randomValue, readAuthioAdminResponse, readWebhookEventData, resolveConnection, resolveIssuer, resourceAccessSourceOf, seconds, systemClock, toBasicAuthorization, toCamelCasedMembers, toClientCredentialsToken, toConnectionExchangeResult, toCredentialClientId, toDevicePollOutcome, toScopeString, toTokenValidationError, tryParseWebhookEvent, verifyAuthioJwt, verifyWebhookSignature };
|
|
1239
1915
|
//# sourceMappingURL=index.js.map
|
|
1240
1916
|
//# sourceMappingURL=index.js.map
|