@insaeng/auth 0.0.0 → 0.3.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.
Files changed (33) hide show
  1. package/dist/data/auth/auth-repo.d.ts +7 -0
  2. package/dist/data/auth/auth-repo.d.ts.map +1 -0
  3. package/dist/data/auth/auth-repo.js +43 -0
  4. package/dist/data/sources/jwks/jwks-source.d.ts +22 -0
  5. package/dist/data/sources/jwks/jwks-source.d.ts.map +1 -0
  6. package/dist/data/sources/jwks/jwks-source.js +46 -0
  7. package/dist/data/sources/jwks/test-issuer-source.d.ts +21 -0
  8. package/dist/data/sources/jwks/test-issuer-source.d.ts.map +1 -0
  9. package/dist/data/sources/jwks/test-issuer-source.js +28 -0
  10. package/dist/dependencies.d.ts +12 -0
  11. package/dist/dependencies.d.ts.map +1 -0
  12. package/dist/dependencies.js +13 -0
  13. package/dist/domain/auth/auth-entity.d.ts +20 -0
  14. package/dist/domain/auth/auth-entity.d.ts.map +1 -0
  15. package/dist/domain/auth/auth-entity.js +14 -0
  16. package/dist/domain/auth/auth-repo.d.ts +6 -0
  17. package/dist/domain/auth/auth-repo.d.ts.map +1 -0
  18. package/dist/domain/auth/auth-repo.js +1 -0
  19. package/dist/domain/auth/use-cases/assert-can-use-case.d.ts +8 -0
  20. package/dist/domain/auth/use-cases/assert-can-use-case.d.ts.map +1 -0
  21. package/dist/domain/auth/use-cases/assert-can-use-case.js +8 -0
  22. package/dist/domain/auth/use-cases/verify-access-token-use-case.d.ts +8 -0
  23. package/dist/domain/auth/use-cases/verify-access-token-use-case.d.ts.map +1 -0
  24. package/dist/domain/auth/use-cases/verify-access-token-use-case.js +13 -0
  25. package/package.json +38 -2
  26. package/src/data/auth/auth-repo.ts +58 -0
  27. package/src/data/sources/jwks/jwks-source.ts +85 -0
  28. package/src/data/sources/jwks/test-issuer-source.ts +65 -0
  29. package/src/dependencies.ts +28 -0
  30. package/src/domain/auth/auth-entity.ts +29 -0
  31. package/src/domain/auth/auth-repo.ts +10 -0
  32. package/src/domain/auth/use-cases/assert-can-use-case.ts +22 -0
  33. package/src/domain/auth/use-cases/verify-access-token-use-case.ts +23 -0
@@ -0,0 +1,7 @@
1
+ import type { AuthRepo } from "../../domain/auth/auth-repo.js";
2
+ import type { JwksSource } from "../sources/jwks/jwks-source.js";
3
+ export interface AuthRepoDeps {
4
+ jwks: JwksSource;
5
+ }
6
+ export declare function createAuthRepo({ jwks, }: AuthRepoDeps): Pick<AuthRepo, "findPrincipal">;
7
+ //# sourceMappingURL=auth-repo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-repo.d.ts","sourceRoot":"","sources":["../../../src/data/auth/auth-repo.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,KAAK,EAEV,UAAU,EACX,MAAM,gCAAgC,CAAC;AAExC,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,UAAU,CAAC;CAClB;AAgCD,wBAAgB,cAAc,CAAC,EAC7B,IAAI,GACL,EAAE,YAAY,GAAG,IAAI,CAAC,QAAQ,EAAE,eAAe,CAAC,CAahD"}
@@ -0,0 +1,43 @@
1
+ import { errors } from "jose";
2
+ const rejectedTokenErrors = [
3
+ errors.JWTClaimValidationFailed,
4
+ errors.JWTExpired,
5
+ errors.JWTInvalid,
6
+ errors.JWSInvalid,
7
+ errors.JWSSignatureVerificationFailed,
8
+ errors.JWKSNoMatchingKey,
9
+ errors.JOSEAlgNotAllowed,
10
+ errors.JOSENotSupported,
11
+ ];
12
+ function isRejectedToken(error) {
13
+ return rejectedTokenErrors.some((rejected) => error instanceof rejected);
14
+ }
15
+ function toPrincipal(claims) {
16
+ const principal = {
17
+ kind: claims.client_id === claims.sub ? "client" : "user",
18
+ id: claims.sub,
19
+ roles: claims.roles,
20
+ };
21
+ if (claims.email !== undefined) {
22
+ principal.email = claims.email;
23
+ }
24
+ if (claims.name !== undefined) {
25
+ principal.name = claims.name;
26
+ }
27
+ return principal;
28
+ }
29
+ export function createAuthRepo({ jwks, }) {
30
+ return {
31
+ async findPrincipal(accessToken) {
32
+ try {
33
+ return toPrincipal(await jwks.verify(accessToken));
34
+ }
35
+ catch (error) {
36
+ if (isRejectedToken(error)) {
37
+ return undefined;
38
+ }
39
+ throw error;
40
+ }
41
+ },
42
+ };
43
+ }
@@ -0,0 +1,22 @@
1
+ import { type JWTVerifyGetKey } from "jose";
2
+ export interface AccessTokenClaims {
3
+ sub: string;
4
+ roles: string[];
5
+ client_id?: string;
6
+ email?: string;
7
+ name?: string;
8
+ }
9
+ export type JwksKeys = {
10
+ jwksUrl: string | URL;
11
+ } | {
12
+ keys: JWTVerifyGetKey;
13
+ };
14
+ export type JwksSourceOptions = JwksKeys & {
15
+ issuer: string;
16
+ audience: string;
17
+ };
18
+ export interface JwksSource {
19
+ verify(accessToken: string): Promise<AccessTokenClaims>;
20
+ }
21
+ export declare function createJwksSource(options: JwksSourceOptions): JwksSource;
22
+ //# sourceMappingURL=jwks-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwks-source.d.ts","sourceRoot":"","sources":["../../../../src/data/sources/jwks/jwks-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,eAAe,EACrB,MAAM,MAAM,CAAC;AAEd,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,QAAQ,GAAG;IAAE,OAAO,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,CAAC;AAE7E,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CACzD;AA0CD,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,UAAU,CAiBvE"}
@@ -0,0 +1,46 @@
1
+ import { createRemoteJWKSet, errors, jwtVerify, } from "jose";
2
+ function invalidClaim(payload, claim, message) {
3
+ throw new errors.JWTClaimValidationFailed(message, payload, claim, "invalid");
4
+ }
5
+ function optionalString(payload, claim) {
6
+ const value = payload[claim];
7
+ if (value !== undefined && typeof value !== "string") {
8
+ invalidClaim(payload, claim, `"${claim}" claim must be a string`);
9
+ }
10
+ return value;
11
+ }
12
+ function toClaims(payload) {
13
+ const { sub, roles } = payload;
14
+ if (typeof sub !== "string" || sub === "") {
15
+ invalidClaim(payload, "sub", '"sub" claim must be a non-empty string');
16
+ }
17
+ if (!Array.isArray(roles) ||
18
+ !roles.every((role) => typeof role === "string")) {
19
+ invalidClaim(payload, "roles", '"roles" claim must be an array of strings');
20
+ }
21
+ const claims = { sub, roles };
22
+ for (const claim of ["client_id", "email", "name"]) {
23
+ const value = optionalString(payload, claim);
24
+ if (value !== undefined) {
25
+ claims[claim] = value;
26
+ }
27
+ }
28
+ return claims;
29
+ }
30
+ export function createJwksSource(options) {
31
+ const keys = "keys" in options
32
+ ? options.keys
33
+ : createRemoteJWKSet(new URL(options.jwksUrl));
34
+ return {
35
+ async verify(accessToken) {
36
+ const { payload } = await jwtVerify(accessToken, keys, {
37
+ typ: "at+jwt",
38
+ issuer: options.issuer,
39
+ audience: options.audience,
40
+ algorithms: ["EdDSA"],
41
+ requiredClaims: ["exp", "sub"],
42
+ });
43
+ return toClaims(payload);
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,21 @@
1
+ import { type JSONWebKeySet, type JWTVerifyGetKey } from "jose";
2
+ import type { AccessTokenClaims } from "./jwks-source.js";
3
+ export interface TestIssuerOptions {
4
+ issuer?: string;
5
+ audience?: string;
6
+ }
7
+ export interface SignTestTokenOptions {
8
+ typ?: string;
9
+ issuer?: string;
10
+ audience?: string;
11
+ expirationTime?: string | number | Date;
12
+ }
13
+ export interface TestIssuer {
14
+ issuer: string;
15
+ audience: string;
16
+ jwks: JSONWebKeySet;
17
+ keys: JWTVerifyGetKey;
18
+ signAccessToken(claims: Partial<AccessTokenClaims>, options?: SignTestTokenOptions): Promise<string>;
19
+ }
20
+ export declare function createTestIssuerSource({ issuer, audience, }?: TestIssuerOptions): Promise<TestIssuer>;
21
+ //# sourceMappingURL=test-issuer-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-issuer-source.d.ts","sourceRoot":"","sources":["../../../../src/data/sources/jwks/test-issuer-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,MAAM,MAAM,CAAC;AACd,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,oBAAoB;IACnC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CACzC;AAED,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,aAAa,CAAC;IACpB,IAAI,EAAE,eAAe,CAAC;IACtB,eAAe,CACb,MAAM,EAAE,OAAO,CAAC,iBAAiB,CAAC,EAClC,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAsB,sBAAsB,CAAC,EAC3C,MAAoC,EACpC,QAAiC,GAClC,GAAE,iBAAsB,GAAG,OAAO,CAAC,UAAU,CAAC,CA2B9C"}
@@ -0,0 +1,28 @@
1
+ import { calculateJwkThumbprint, createLocalJWKSet, exportJWK, generateKeyPair, SignJWT, } from "jose";
2
+ export async function createTestIssuerSource({ issuer = "https://auth.insaeng.test", audience = "insaeng-test-service", } = {}) {
3
+ const { privateKey, publicKey } = await generateKeyPair("EdDSA", {
4
+ crv: "Ed25519",
5
+ });
6
+ const jwk = await exportJWK(publicKey);
7
+ const kid = await calculateJwkThumbprint(jwk);
8
+ const jwks = {
9
+ keys: [{ ...jwk, kid, alg: "EdDSA", use: "sig" }],
10
+ };
11
+ return {
12
+ issuer,
13
+ audience,
14
+ jwks,
15
+ keys: createLocalJWKSet(jwks),
16
+ async signAccessToken(claims, options = {}) {
17
+ const { sub = "test-user", roles = [], ...rest } = claims;
18
+ return new SignJWT({ roles, ...rest })
19
+ .setProtectedHeader({ alg: "EdDSA", typ: options.typ ?? "at+jwt", kid })
20
+ .setSubject(sub)
21
+ .setIssuer(options.issuer ?? issuer)
22
+ .setAudience(options.audience ?? audience)
23
+ .setIssuedAt()
24
+ .setExpirationTime(options.expirationTime ?? "5m")
25
+ .sign(privateKey);
26
+ },
27
+ };
28
+ }
@@ -0,0 +1,12 @@
1
+ import { type JwksSourceOptions } from "./data/sources/jwks/jwks-source.js";
2
+ import type { AuthRepo } from "./domain/auth/auth-repo.js";
3
+ import { verifyAccessTokenUseCase, type VerifyAccessToken } from "./domain/auth/use-cases/verify-access-token-use-case.js";
4
+ export type { JwksSourceOptions };
5
+ export { assertCanUseCase } from "./domain/auth/use-cases/assert-can-use-case.js";
6
+ export { verifyAccessTokenUseCase };
7
+ export interface Auth {
8
+ authRepo: Pick<AuthRepo, "findPrincipal">;
9
+ verifyAccessToken: VerifyAccessToken;
10
+ }
11
+ export declare function createAuth(options: JwksSourceOptions): Auth;
12
+ //# sourceMappingURL=dependencies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dependencies.d.ts","sourceRoot":"","sources":["../src/dependencies.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,wBAAwB,EACxB,KAAK,iBAAiB,EACvB,MAAM,yDAAyD,CAAC;AAEjE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,MAAM,gDAAgD,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,CAAC;AAEpC,MAAM,WAAW,IAAI;IACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,eAAe,CAAC,CAAC;IAC1C,iBAAiB,EAAE,iBAAiB,CAAC;CACtC;AAED,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAO3D"}
@@ -0,0 +1,13 @@
1
+ import { createAuthRepo } from "./data/auth/auth-repo.js";
2
+ import { createJwksSource, } from "./data/sources/jwks/jwks-source.js";
3
+ import { verifyAccessTokenUseCase, } from "./domain/auth/use-cases/verify-access-token-use-case.js";
4
+ export { assertCanUseCase } from "./domain/auth/use-cases/assert-can-use-case.js";
5
+ export { verifyAccessTokenUseCase };
6
+ export function createAuth(options) {
7
+ const jwks = createJwksSource(options);
8
+ const authRepo = createAuthRepo({ jwks });
9
+ return {
10
+ authRepo,
11
+ verifyAccessToken: verifyAccessTokenUseCase({ authRepo }),
12
+ };
13
+ }
@@ -0,0 +1,20 @@
1
+ export type { AuthRepo } from "./auth-repo.js";
2
+ export type { AssertCan } from "./use-cases/assert-can-use-case.js";
3
+ export type { VerifyAccessToken } from "./use-cases/verify-access-token-use-case.js";
4
+ export interface Principal {
5
+ kind: "user" | "client";
6
+ id: string;
7
+ roles: readonly string[];
8
+ email?: string;
9
+ name?: string;
10
+ }
11
+ export declare class Unauthenticated extends Error {
12
+ readonly name = "Unauthenticated";
13
+ constructor();
14
+ }
15
+ export declare class Forbidden<Action extends string = string> extends Error {
16
+ readonly name = "Forbidden";
17
+ readonly action: Action;
18
+ constructor(action: Action);
19
+ }
20
+ //# sourceMappingURL=auth-entity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-entity.d.ts","sourceRoot":"","sources":["../../../src/domain/auth/auth-entity.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,YAAY,EAAE,SAAS,EAAE,MAAM,oCAAoC,CAAC;AACpE,YAAY,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,qBAAa,eAAgB,SAAQ,KAAK;IACxC,SAAkB,IAAI,qBAAqB;;CAK5C;AAED,qBAAa,SAAS,CAAC,MAAM,SAAS,MAAM,GAAG,MAAM,CAAE,SAAQ,KAAK;IAClE,SAAkB,IAAI,eAAe;IACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;gBAEZ,MAAM,EAAE,MAAM;CAI3B"}
@@ -0,0 +1,14 @@
1
+ export class Unauthenticated extends Error {
2
+ name = "Unauthenticated";
3
+ constructor() {
4
+ super("Unauthenticated");
5
+ }
6
+ }
7
+ export class Forbidden extends Error {
8
+ name = "Forbidden";
9
+ action;
10
+ constructor(action) {
11
+ super(`Forbidden: ${action}`);
12
+ this.action = action;
13
+ }
14
+ }
@@ -0,0 +1,6 @@
1
+ import type { Principal } from "./auth-entity.js";
2
+ export interface AuthRepo<Action extends string = string, Resource = unknown> {
3
+ findPrincipal(accessToken: string): Promise<Principal | undefined>;
4
+ can(principal: Principal, action: Action, resource: Resource): Promise<boolean>;
5
+ }
6
+ //# sourceMappingURL=auth-repo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-repo.d.ts","sourceRoot":"","sources":["../../../src/domain/auth/auth-repo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,WAAW,QAAQ,CAAC,MAAM,SAAS,MAAM,GAAG,MAAM,EAAE,QAAQ,GAAG,OAAO;IAC1E,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC;IACnE,GAAG,CACD,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,QAAQ,GACjB,OAAO,CAAC,OAAO,CAAC,CAAC;CACrB"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import { type Principal } from "../auth-entity.js";
2
+ import type { AuthRepo } from "../auth-repo.js";
3
+ export type AssertCan<Action extends string, Resource> = (principal: Principal, action: Action, resource: Resource) => Promise<void>;
4
+ export interface AssertCanDeps<Action extends string, Resource> {
5
+ authRepo: Pick<AuthRepo<Action, Resource>, "can">;
6
+ }
7
+ export declare function assertCanUseCase<Action extends string, Resource>({ authRepo, }: AssertCanDeps<Action, Resource>): AssertCan<Action, Resource>;
8
+ //# sourceMappingURL=assert-can-use-case.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assert-can-use-case.d.ts","sourceRoot":"","sources":["../../../../src/domain/auth/use-cases/assert-can-use-case.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,MAAM,SAAS,CAAC,MAAM,SAAS,MAAM,EAAE,QAAQ,IAAI,CACvD,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,QAAQ,KACf,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnB,MAAM,WAAW,aAAa,CAAC,MAAM,SAAS,MAAM,EAAE,QAAQ;IAC5D,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,KAAK,CAAC,CAAC;CACnD;AAED,wBAAgB,gBAAgB,CAAC,MAAM,SAAS,MAAM,EAAE,QAAQ,EAAE,EAChE,QAAQ,GACT,EAAE,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAM/D"}
@@ -0,0 +1,8 @@
1
+ import { Forbidden } from "../auth-entity.js";
2
+ export function assertCanUseCase({ authRepo, }) {
3
+ return async (principal, action, resource) => {
4
+ if (!(await authRepo.can(principal, action, resource))) {
5
+ throw new Forbidden(action);
6
+ }
7
+ };
8
+ }
@@ -0,0 +1,8 @@
1
+ import { type Principal } from "../auth-entity.js";
2
+ import type { AuthRepo } from "../auth-repo.js";
3
+ export type VerifyAccessToken = (accessToken: string) => Promise<Principal>;
4
+ export interface VerifyAccessTokenDeps {
5
+ authRepo: Pick<AuthRepo, "findPrincipal">;
6
+ }
7
+ export declare function verifyAccessTokenUseCase({ authRepo, }: VerifyAccessTokenDeps): VerifyAccessToken;
8
+ //# sourceMappingURL=verify-access-token-use-case.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-access-token-use-case.d.ts","sourceRoot":"","sources":["../../../../src/domain/auth/use-cases/verify-access-token-use-case.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,MAAM,iBAAiB,GAAG,CAAC,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,CAAC,CAAC;AAE5E,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,eAAe,CAAC,CAAC;CAC3C;AAED,wBAAgB,wBAAwB,CAAC,EACvC,QAAQ,GACT,EAAE,qBAAqB,GAAG,iBAAiB,CAW3C"}
@@ -0,0 +1,13 @@
1
+ import { Unauthenticated } from "../auth-entity.js";
2
+ export function verifyAccessTokenUseCase({ authRepo, }) {
3
+ return async (accessToken) => {
4
+ if (accessToken.trim() === "") {
5
+ throw new Unauthenticated();
6
+ }
7
+ const principal = await authRepo.findPrincipal(accessToken);
8
+ if (principal === undefined) {
9
+ throw new Unauthenticated();
10
+ }
11
+ return principal;
12
+ };
13
+ }
package/package.json CHANGED
@@ -1,10 +1,46 @@
1
1
  {
2
2
  "name": "@insaeng/auth",
3
- "version": "0.0.0",
3
+ "version": "0.3.0",
4
4
  "description": "Access-token verification for insaeng services",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/my-insaeng/insaeng-service-config.git",
8
8
  "directory": "packages/auth"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/dependencies.d.ts",
14
+ "default": "./dist/dependencies.js"
15
+ },
16
+ "./testing": {
17
+ "types": "./dist/data/sources/jwks/test-issuer-source.d.ts",
18
+ "default": "./dist/data/sources/jwks/test-issuer-source.js"
19
+ },
20
+ "./domain": {
21
+ "types": "./dist/domain/auth/auth-entity.d.ts",
22
+ "default": "./dist/domain/auth/auth-entity.js"
23
+ }
24
+ },
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "provenance": true
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "src"
32
+ ],
33
+ "dependencies": {
34
+ "jose": "6.2.19"
35
+ },
36
+ "devDependencies": {
37
+ "@insaeng/tsconfig": "0.1.0",
38
+ "@types/node": "24.19.4",
39
+ "typescript": "6.0.3",
40
+ "vitest": "5.1.2"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.build.json",
44
+ "typecheck": "tsc"
9
45
  }
10
- }
46
+ }
@@ -0,0 +1,58 @@
1
+ import { errors } from "jose";
2
+ import type { Principal } from "../../domain/auth/auth-entity.js";
3
+ import type { AuthRepo } from "../../domain/auth/auth-repo.js";
4
+ import type {
5
+ AccessTokenClaims,
6
+ JwksSource,
7
+ } from "../sources/jwks/jwks-source.js";
8
+
9
+ export interface AuthRepoDeps {
10
+ jwks: JwksSource;
11
+ }
12
+
13
+ const rejectedTokenErrors = [
14
+ errors.JWTClaimValidationFailed,
15
+ errors.JWTExpired,
16
+ errors.JWTInvalid,
17
+ errors.JWSInvalid,
18
+ errors.JWSSignatureVerificationFailed,
19
+ errors.JWKSNoMatchingKey,
20
+ errors.JOSEAlgNotAllowed,
21
+ errors.JOSENotSupported,
22
+ ];
23
+
24
+ function isRejectedToken(error: unknown): boolean {
25
+ return rejectedTokenErrors.some((rejected) => error instanceof rejected);
26
+ }
27
+
28
+ function toPrincipal(claims: AccessTokenClaims): Principal {
29
+ const principal: Principal = {
30
+ kind: claims.client_id === claims.sub ? "client" : "user",
31
+ id: claims.sub,
32
+ roles: claims.roles,
33
+ };
34
+ if (claims.email !== undefined) {
35
+ principal.email = claims.email;
36
+ }
37
+ if (claims.name !== undefined) {
38
+ principal.name = claims.name;
39
+ }
40
+ return principal;
41
+ }
42
+
43
+ export function createAuthRepo({
44
+ jwks,
45
+ }: AuthRepoDeps): Pick<AuthRepo, "findPrincipal"> {
46
+ return {
47
+ async findPrincipal(accessToken) {
48
+ try {
49
+ return toPrincipal(await jwks.verify(accessToken));
50
+ } catch (error) {
51
+ if (isRejectedToken(error)) {
52
+ return undefined;
53
+ }
54
+ throw error;
55
+ }
56
+ },
57
+ };
58
+ }
@@ -0,0 +1,85 @@
1
+ import {
2
+ createRemoteJWKSet,
3
+ errors,
4
+ jwtVerify,
5
+ type JWTPayload,
6
+ type JWTVerifyGetKey,
7
+ } from "jose";
8
+
9
+ export interface AccessTokenClaims {
10
+ sub: string;
11
+ roles: string[];
12
+ client_id?: string;
13
+ email?: string;
14
+ name?: string;
15
+ }
16
+
17
+ export type JwksKeys = { jwksUrl: string | URL } | { keys: JWTVerifyGetKey };
18
+
19
+ export type JwksSourceOptions = JwksKeys & {
20
+ issuer: string;
21
+ audience: string;
22
+ };
23
+
24
+ export interface JwksSource {
25
+ verify(accessToken: string): Promise<AccessTokenClaims>;
26
+ }
27
+
28
+ function invalidClaim(
29
+ payload: JWTPayload,
30
+ claim: string,
31
+ message: string,
32
+ ): never {
33
+ throw new errors.JWTClaimValidationFailed(message, payload, claim, "invalid");
34
+ }
35
+
36
+ function optionalString(
37
+ payload: JWTPayload,
38
+ claim: string,
39
+ ): string | undefined {
40
+ const value = payload[claim];
41
+ if (value !== undefined && typeof value !== "string") {
42
+ invalidClaim(payload, claim, `"${claim}" claim must be a string`);
43
+ }
44
+ return value;
45
+ }
46
+
47
+ function toClaims(payload: JWTPayload): AccessTokenClaims {
48
+ const { sub, roles } = payload;
49
+ if (typeof sub !== "string" || sub === "") {
50
+ invalidClaim(payload, "sub", '"sub" claim must be a non-empty string');
51
+ }
52
+ if (
53
+ !Array.isArray(roles) ||
54
+ !roles.every((role) => typeof role === "string")
55
+ ) {
56
+ invalidClaim(payload, "roles", '"roles" claim must be an array of strings');
57
+ }
58
+ const claims: AccessTokenClaims = { sub, roles };
59
+ for (const claim of ["client_id", "email", "name"] as const) {
60
+ const value = optionalString(payload, claim);
61
+ if (value !== undefined) {
62
+ claims[claim] = value;
63
+ }
64
+ }
65
+ return claims;
66
+ }
67
+
68
+ export function createJwksSource(options: JwksSourceOptions): JwksSource {
69
+ const keys =
70
+ "keys" in options
71
+ ? options.keys
72
+ : createRemoteJWKSet(new URL(options.jwksUrl));
73
+ return {
74
+ async verify(accessToken) {
75
+ const { payload } = await jwtVerify(accessToken, keys, {
76
+ typ: "at+jwt",
77
+ issuer: options.issuer,
78
+ audience: options.audience,
79
+ algorithms: ["EdDSA"],
80
+ requiredClaims: ["exp", "sub"],
81
+ });
82
+ return toClaims(payload);
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,65 @@
1
+ import {
2
+ calculateJwkThumbprint,
3
+ createLocalJWKSet,
4
+ exportJWK,
5
+ generateKeyPair,
6
+ SignJWT,
7
+ type JSONWebKeySet,
8
+ type JWTVerifyGetKey,
9
+ } from "jose";
10
+ import type { AccessTokenClaims } from "./jwks-source.js";
11
+
12
+ export interface TestIssuerOptions {
13
+ issuer?: string;
14
+ audience?: string;
15
+ }
16
+
17
+ export interface SignTestTokenOptions {
18
+ typ?: string;
19
+ issuer?: string;
20
+ audience?: string;
21
+ expirationTime?: string | number | Date;
22
+ }
23
+
24
+ export interface TestIssuer {
25
+ issuer: string;
26
+ audience: string;
27
+ jwks: JSONWebKeySet;
28
+ keys: JWTVerifyGetKey;
29
+ signAccessToken(
30
+ claims: Partial<AccessTokenClaims>,
31
+ options?: SignTestTokenOptions,
32
+ ): Promise<string>;
33
+ }
34
+
35
+ export async function createTestIssuerSource({
36
+ issuer = "https://auth.insaeng.test",
37
+ audience = "insaeng-test-service",
38
+ }: TestIssuerOptions = {}): Promise<TestIssuer> {
39
+ const { privateKey, publicKey } = await generateKeyPair("EdDSA", {
40
+ crv: "Ed25519",
41
+ });
42
+ const jwk = await exportJWK(publicKey);
43
+ const kid = await calculateJwkThumbprint(jwk);
44
+ const jwks: JSONWebKeySet = {
45
+ keys: [{ ...jwk, kid, alg: "EdDSA", use: "sig" }],
46
+ };
47
+
48
+ return {
49
+ issuer,
50
+ audience,
51
+ jwks,
52
+ keys: createLocalJWKSet(jwks),
53
+ async signAccessToken(claims, options = {}) {
54
+ const { sub = "test-user", roles = [], ...rest } = claims;
55
+ return new SignJWT({ roles, ...rest })
56
+ .setProtectedHeader({ alg: "EdDSA", typ: options.typ ?? "at+jwt", kid })
57
+ .setSubject(sub)
58
+ .setIssuer(options.issuer ?? issuer)
59
+ .setAudience(options.audience ?? audience)
60
+ .setIssuedAt()
61
+ .setExpirationTime(options.expirationTime ?? "5m")
62
+ .sign(privateKey);
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,28 @@
1
+ import { createAuthRepo } from "./data/auth/auth-repo.js";
2
+ import {
3
+ createJwksSource,
4
+ type JwksSourceOptions,
5
+ } from "./data/sources/jwks/jwks-source.js";
6
+ import type { AuthRepo } from "./domain/auth/auth-repo.js";
7
+ import {
8
+ verifyAccessTokenUseCase,
9
+ type VerifyAccessToken,
10
+ } from "./domain/auth/use-cases/verify-access-token-use-case.js";
11
+
12
+ export type { JwksSourceOptions };
13
+ export { assertCanUseCase } from "./domain/auth/use-cases/assert-can-use-case.js";
14
+ export { verifyAccessTokenUseCase };
15
+
16
+ export interface Auth {
17
+ authRepo: Pick<AuthRepo, "findPrincipal">;
18
+ verifyAccessToken: VerifyAccessToken;
19
+ }
20
+
21
+ export function createAuth(options: JwksSourceOptions): Auth {
22
+ const jwks = createJwksSource(options);
23
+ const authRepo = createAuthRepo({ jwks });
24
+ return {
25
+ authRepo,
26
+ verifyAccessToken: verifyAccessTokenUseCase({ authRepo }),
27
+ };
28
+ }
@@ -0,0 +1,29 @@
1
+ export type { AuthRepo } from "./auth-repo.js";
2
+ export type { AssertCan } from "./use-cases/assert-can-use-case.js";
3
+ export type { VerifyAccessToken } from "./use-cases/verify-access-token-use-case.js";
4
+
5
+ export interface Principal {
6
+ kind: "user" | "client";
7
+ id: string;
8
+ roles: readonly string[];
9
+ email?: string;
10
+ name?: string;
11
+ }
12
+
13
+ export class Unauthenticated extends Error {
14
+ override readonly name = "Unauthenticated";
15
+
16
+ constructor() {
17
+ super("Unauthenticated");
18
+ }
19
+ }
20
+
21
+ export class Forbidden<Action extends string = string> extends Error {
22
+ override readonly name = "Forbidden";
23
+ readonly action: Action;
24
+
25
+ constructor(action: Action) {
26
+ super(`Forbidden: ${action}`);
27
+ this.action = action;
28
+ }
29
+ }
@@ -0,0 +1,10 @@
1
+ import type { Principal } from "./auth-entity.js";
2
+
3
+ export interface AuthRepo<Action extends string = string, Resource = unknown> {
4
+ findPrincipal(accessToken: string): Promise<Principal | undefined>;
5
+ can(
6
+ principal: Principal,
7
+ action: Action,
8
+ resource: Resource,
9
+ ): Promise<boolean>;
10
+ }
@@ -0,0 +1,22 @@
1
+ import { Forbidden, type Principal } from "../auth-entity.js";
2
+ import type { AuthRepo } from "../auth-repo.js";
3
+
4
+ export type AssertCan<Action extends string, Resource> = (
5
+ principal: Principal,
6
+ action: Action,
7
+ resource: Resource,
8
+ ) => Promise<void>;
9
+
10
+ export interface AssertCanDeps<Action extends string, Resource> {
11
+ authRepo: Pick<AuthRepo<Action, Resource>, "can">;
12
+ }
13
+
14
+ export function assertCanUseCase<Action extends string, Resource>({
15
+ authRepo,
16
+ }: AssertCanDeps<Action, Resource>): AssertCan<Action, Resource> {
17
+ return async (principal, action, resource) => {
18
+ if (!(await authRepo.can(principal, action, resource))) {
19
+ throw new Forbidden(action);
20
+ }
21
+ };
22
+ }
@@ -0,0 +1,23 @@
1
+ import { Unauthenticated, type Principal } from "../auth-entity.js";
2
+ import type { AuthRepo } from "../auth-repo.js";
3
+
4
+ export type VerifyAccessToken = (accessToken: string) => Promise<Principal>;
5
+
6
+ export interface VerifyAccessTokenDeps {
7
+ authRepo: Pick<AuthRepo, "findPrincipal">;
8
+ }
9
+
10
+ export function verifyAccessTokenUseCase({
11
+ authRepo,
12
+ }: VerifyAccessTokenDeps): VerifyAccessToken {
13
+ return async (accessToken) => {
14
+ if (accessToken.trim() === "") {
15
+ throw new Unauthenticated();
16
+ }
17
+ const principal = await authRepo.findPrincipal(accessToken);
18
+ if (principal === undefined) {
19
+ throw new Unauthenticated();
20
+ }
21
+ return principal;
22
+ };
23
+ }