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

oauthScope.ts

40 lines1.1 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 first-seen order.
5 */
6export function parseOAuthScope(value: string): ReadonlyArray<string> | null {
7 if (value.length === 0) {
8 return null;
9 }
10​
11 const scopes = value.split(" ");
12 if (scopes.some((scope) => !OAUTH_SCOPE_TOKEN.test(scope))) {
13 return null;
14 }
15​
16 return [...new Set(scopes)];
18​
19export function encodeOAuthScope(scopes: ReadonlyArray<string>): string {
20 const encoded = scopes.join(" ");
21 const parsed = parseOAuthScope(encoded);
22 if (parsed === null || parsed.length !== scopes.length) {
23 throw new Error("OAuth scopes must be non-empty, valid, and unique.");
24 }
25 return encoded;
27​
28export function parseAllowedOAuthScope<Scope extends string>(input: {
29 readonly value: string;
30 readonly allowedScopes: ReadonlySet<Scope>;
31}): ReadonlyArray<Scope> | null {
32 const scopes = parseOAuthScope(input.value);
33 if (
34 scopes === null ||
35 !scopes.every((scope): scope is Scope => input.allowedScopes.has(scope as Scope))
36 ) {
37 return null;
38 }
39 return scopes;