@insaeng/auth 0.3.0 → 0.4.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.
@@ -0,0 +1,18 @@
1
+ import { type JWK } from "jose";
2
+ export interface OauthSourceOptions {
3
+ tokenEndpoint: string | URL;
4
+ clientId: string;
5
+ privateKey: JWK;
6
+ resource: string;
7
+ fetch?: typeof fetch;
8
+ }
9
+ export interface OauthSource {
10
+ getToken(): Promise<string>;
11
+ }
12
+ export declare class TokenRequestError extends Error {
13
+ readonly status: number;
14
+ readonly error: string | undefined;
15
+ constructor(status: number, error: string | undefined);
16
+ }
17
+ export declare function createOauthSource(options: OauthSourceOptions): OauthSource;
18
+ //# sourceMappingURL=oauth-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-source.d.ts","sourceRoot":"","sources":["../../../../src/data/sources/oauth/oauth-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,GAAG,EAAE,MAAM,MAAM,CAAC;AAEpD,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,MAAM,GAAG,GAAG,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,GAAG,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC7B;AAED,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;gBAEvB,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS;CAStD;AA8CD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAkE1E"}
@@ -0,0 +1,104 @@
1
+ import { importJWK, SignJWT } from "jose";
2
+ export class TokenRequestError extends Error {
3
+ status;
4
+ error;
5
+ constructor(status, error) {
6
+ super(`Token request failed with status ${String(status)}` +
7
+ (error === undefined ? "" : `: ${error}`));
8
+ this.name = "TokenRequestError";
9
+ this.status = status;
10
+ this.error = error;
11
+ }
12
+ }
13
+ const ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
14
+ const ASSERTION_LIFETIME_SECONDS = 60;
15
+ const REFRESH_MARGIN_MS = 30_000;
16
+ function isRecord(value) {
17
+ return typeof value === "object" && value !== null;
18
+ }
19
+ async function readJson(response) {
20
+ try {
21
+ return await response.json();
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ function toCachedToken(body) {
28
+ if (!isRecord(body)) {
29
+ throw new TypeError("Token response must be a JSON object");
30
+ }
31
+ const { access_token, expires_in } = body;
32
+ if (typeof access_token !== "string" || access_token === "") {
33
+ throw new TypeError('Token response "access_token" must be a string');
34
+ }
35
+ if (typeof expires_in !== "number" ||
36
+ !Number.isFinite(expires_in) ||
37
+ expires_in <= 0) {
38
+ throw new TypeError('Token response "expires_in" must be a positive number');
39
+ }
40
+ return {
41
+ accessToken: access_token,
42
+ expiresAt: Date.now() + expires_in * 1000,
43
+ };
44
+ }
45
+ export function createOauthSource(options) {
46
+ const { clientId, privateKey, resource } = options;
47
+ const tokenEndpoint = String(options.tokenEndpoint);
48
+ const fetchToken = options.fetch ?? globalThis.fetch;
49
+ const kid = privateKey.kid ?? "";
50
+ if (kid === "") {
51
+ throw new TypeError('Client private key must have a "kid"');
52
+ }
53
+ let key;
54
+ let cached;
55
+ let pending;
56
+ async function signAssertion() {
57
+ key ??= importJWK(privateKey, "EdDSA");
58
+ return new SignJWT()
59
+ .setProtectedHeader({ alg: "EdDSA", kid })
60
+ .setIssuer(clientId)
61
+ .setSubject(clientId)
62
+ .setAudience(tokenEndpoint)
63
+ .setJti(crypto.randomUUID())
64
+ .setIssuedAt()
65
+ .setExpirationTime(`${String(ASSERTION_LIFETIME_SECONDS)}s`)
66
+ .sign(await key);
67
+ }
68
+ async function requestToken() {
69
+ const response = await fetchToken(tokenEndpoint, {
70
+ method: "POST",
71
+ headers: {
72
+ accept: "application/json",
73
+ "content-type": "application/x-www-form-urlencoded",
74
+ },
75
+ body: new URLSearchParams({
76
+ grant_type: "client_credentials",
77
+ client_assertion_type: ASSERTION_TYPE,
78
+ client_assertion: await signAssertion(),
79
+ resource,
80
+ }),
81
+ });
82
+ const body = await readJson(response);
83
+ if (!response.ok) {
84
+ const error = isRecord(body) && typeof body.error === "string"
85
+ ? body.error
86
+ : undefined;
87
+ throw new TokenRequestError(response.status, error);
88
+ }
89
+ cached = toCachedToken(body);
90
+ return cached.accessToken;
91
+ }
92
+ return {
93
+ getToken() {
94
+ if (cached !== undefined &&
95
+ cached.expiresAt - Date.now() > REFRESH_MARGIN_MS) {
96
+ return Promise.resolve(cached.accessToken);
97
+ }
98
+ pending ??= requestToken().finally(() => {
99
+ pending = undefined;
100
+ });
101
+ return pending;
102
+ },
103
+ };
104
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insaeng/auth",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Access-token verification for insaeng services",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,6 +13,10 @@
13
13
  "types": "./dist/dependencies.d.ts",
14
14
  "default": "./dist/dependencies.js"
15
15
  },
16
+ "./client": {
17
+ "types": "./dist/data/sources/oauth/oauth-source.d.ts",
18
+ "default": "./dist/data/sources/oauth/oauth-source.js"
19
+ },
16
20
  "./testing": {
17
21
  "types": "./dist/data/sources/jwks/test-issuer-source.d.ts",
18
22
  "default": "./dist/data/sources/jwks/test-issuer-source.js"
@@ -0,0 +1,140 @@
1
+ import { importJWK, SignJWT, type JWK } from "jose";
2
+
3
+ export interface OauthSourceOptions {
4
+ tokenEndpoint: string | URL;
5
+ clientId: string;
6
+ privateKey: JWK;
7
+ resource: string;
8
+ fetch?: typeof fetch;
9
+ }
10
+
11
+ export interface OauthSource {
12
+ getToken(): Promise<string>;
13
+ }
14
+
15
+ export class TokenRequestError extends Error {
16
+ readonly status: number;
17
+ readonly error: string | undefined;
18
+
19
+ constructor(status: number, error: string | undefined) {
20
+ super(
21
+ `Token request failed with status ${String(status)}` +
22
+ (error === undefined ? "" : `: ${error}`),
23
+ );
24
+ this.name = "TokenRequestError";
25
+ this.status = status;
26
+ this.error = error;
27
+ }
28
+ }
29
+
30
+ const ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
31
+ const ASSERTION_LIFETIME_SECONDS = 60;
32
+ const REFRESH_MARGIN_MS = 30_000;
33
+
34
+ interface CachedToken {
35
+ accessToken: string;
36
+ expiresAt: number;
37
+ }
38
+
39
+ function isRecord(value: unknown): value is Record<string, unknown> {
40
+ return typeof value === "object" && value !== null;
41
+ }
42
+
43
+ async function readJson(response: Response): Promise<unknown> {
44
+ try {
45
+ return await response.json();
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ function toCachedToken(body: unknown): CachedToken {
52
+ if (!isRecord(body)) {
53
+ throw new TypeError("Token response must be a JSON object");
54
+ }
55
+ const { access_token, expires_in } = body;
56
+ if (typeof access_token !== "string" || access_token === "") {
57
+ throw new TypeError('Token response "access_token" must be a string');
58
+ }
59
+ if (
60
+ typeof expires_in !== "number" ||
61
+ !Number.isFinite(expires_in) ||
62
+ expires_in <= 0
63
+ ) {
64
+ throw new TypeError(
65
+ 'Token response "expires_in" must be a positive number',
66
+ );
67
+ }
68
+ return {
69
+ accessToken: access_token,
70
+ expiresAt: Date.now() + expires_in * 1000,
71
+ };
72
+ }
73
+
74
+ export function createOauthSource(options: OauthSourceOptions): OauthSource {
75
+ const { clientId, privateKey, resource } = options;
76
+ const tokenEndpoint = String(options.tokenEndpoint);
77
+ const fetchToken = options.fetch ?? globalThis.fetch;
78
+ const kid = privateKey.kid ?? "";
79
+ if (kid === "") {
80
+ throw new TypeError('Client private key must have a "kid"');
81
+ }
82
+
83
+ let key: ReturnType<typeof importJWK> | undefined;
84
+ let cached: CachedToken | undefined;
85
+ let pending: Promise<string> | undefined;
86
+
87
+ async function signAssertion(): Promise<string> {
88
+ key ??= importJWK(privateKey, "EdDSA");
89
+ return new SignJWT()
90
+ .setProtectedHeader({ alg: "EdDSA", kid })
91
+ .setIssuer(clientId)
92
+ .setSubject(clientId)
93
+ .setAudience(tokenEndpoint)
94
+ .setJti(crypto.randomUUID())
95
+ .setIssuedAt()
96
+ .setExpirationTime(`${String(ASSERTION_LIFETIME_SECONDS)}s`)
97
+ .sign(await key);
98
+ }
99
+
100
+ async function requestToken(): Promise<string> {
101
+ const response = await fetchToken(tokenEndpoint, {
102
+ method: "POST",
103
+ headers: {
104
+ accept: "application/json",
105
+ "content-type": "application/x-www-form-urlencoded",
106
+ },
107
+ body: new URLSearchParams({
108
+ grant_type: "client_credentials",
109
+ client_assertion_type: ASSERTION_TYPE,
110
+ client_assertion: await signAssertion(),
111
+ resource,
112
+ }),
113
+ });
114
+ const body = await readJson(response);
115
+ if (!response.ok) {
116
+ const error =
117
+ isRecord(body) && typeof body.error === "string"
118
+ ? body.error
119
+ : undefined;
120
+ throw new TokenRequestError(response.status, error);
121
+ }
122
+ cached = toCachedToken(body);
123
+ return cached.accessToken;
124
+ }
125
+
126
+ return {
127
+ getToken() {
128
+ if (
129
+ cached !== undefined &&
130
+ cached.expiresAt - Date.now() > REFRESH_MARGIN_MS
131
+ ) {
132
+ return Promise.resolve(cached.accessToken);
133
+ }
134
+ pending ??= requestToken().finally(() => {
135
+ pending = undefined;
136
+ });
137
+ return pending;
138
+ },
139
+ };
140
+ }