Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

oauthScope.ts

50 lines1.4 KB

1const OAUTH_SCOPE_TOKEN = /^[\u0021\u0023-\u005b\u005d-\u007e]+$/u;
2​
3/**
4 * Decodes an RFC 6749 `scope` value as a set while preserving its first-seen
5 * order for canonical responses and logs.
6 */
7export function parseOAuthScope(value: string): ReadonlyArray<string> | null {
8 if (value.length === 0) {
9 return null;
10 }
11​
12 const scopes = value.split(" ");
13 if (scopes.some((scope) => !OAUTH_SCOPE_TOKEN.test(scope))) {
14 return null;
15 }
16​
17 return [...new Set(scopes)];
19​
20export function encodeOAuthScope(scopes: ReadonlyArray<string>): string {
21 const encoded = scopes.join(" ");
22 const parsed = parseOAuthScope(encoded);
23 if (parsed === null || parsed.length !== scopes.length) {
24 throw new Error("OAuth scopes must be non-empty, valid, and unique.");
25 }
26 return encoded;
28​
29export function oauthScopeSetEquals(value: string, expectedScopes: ReadonlyArray<string>): boolean {
30 const scopes = parseOAuthScope(value);
31 return (
32 scopes !== null &&
33 scopes.length === new Set(expectedScopes).size &&
34 scopes.every((scope) => expectedScopes.includes(scope))
35 );
37​
38export function parseAllowedOAuthScope<Scope extends string>(input: {
39 readonly value: string;
40 readonly allowedScopes: ReadonlySet<Scope>;
41}): ReadonlyArray<Scope> | null {
42 const scopes = parseOAuthScope(input.value);
43 if (
44 scopes === null ||
45 !scopes.every((scope): scope is Scope => input.allowedScopes.has(scope as Scope))
46 ) {
47 return null;
48 }
49 return scopes;