@insaeng/auth 0.3.0 → 0.5.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 (45) hide show
  1. package/dist/app/cli/types-command.d.ts +11 -0
  2. package/dist/app/cli/types-command.d.ts.map +1 -0
  3. package/dist/app/cli/types-command.js +45 -0
  4. package/dist/app/http/auth-error-handler.d.ts +3 -0
  5. package/dist/app/http/auth-error-handler.d.ts.map +1 -0
  6. package/dist/app/http/auth-error-handler.js +29 -0
  7. package/dist/app/http/auth-middleware.d.ts +16 -0
  8. package/dist/app/http/auth-middleware.d.ts.map +1 -0
  9. package/dist/app/http/auth-middleware.js +73 -0
  10. package/dist/data/auth/auth-repo.d.ts +8 -1
  11. package/dist/data/auth/auth-repo.d.ts.map +1 -1
  12. package/dist/data/auth/auth-repo.js +23 -1
  13. package/dist/data/sources/cedar/cedar-schema-source.d.ts +3 -0
  14. package/dist/data/sources/cedar/cedar-schema-source.d.ts.map +1 -0
  15. package/dist/data/sources/cedar/cedar-schema-source.js +67 -0
  16. package/dist/data/sources/cedar/cedar-source.d.ts +17 -0
  17. package/dist/data/sources/cedar/cedar-source.d.ts.map +1 -0
  18. package/dist/data/sources/cedar/cedar-source.js +75 -0
  19. package/dist/data/sources/oauth/oauth-source.d.ts +18 -0
  20. package/dist/data/sources/oauth/oauth-source.d.ts.map +1 -0
  21. package/dist/data/sources/oauth/oauth-source.js +104 -0
  22. package/dist/dependencies.d.ts +10 -5
  23. package/dist/dependencies.d.ts.map +1 -1
  24. package/dist/dependencies.js +7 -4
  25. package/dist/domain/authz-types/authz-types-entity.d.ts +37 -0
  26. package/dist/domain/authz-types/authz-types-entity.d.ts.map +1 -0
  27. package/dist/domain/authz-types/authz-types-entity.js +1 -0
  28. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.d.ts +4 -0
  29. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.d.ts.map +1 -0
  30. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.js +64 -0
  31. package/dist/main.d.ts +3 -0
  32. package/dist/main.d.ts.map +1 -0
  33. package/dist/main.js +11 -0
  34. package/package.json +29 -2
  35. package/src/app/cli/types-command.ts +62 -0
  36. package/src/app/http/auth-error-handler.ts +39 -0
  37. package/src/app/http/auth-middleware.ts +104 -0
  38. package/src/data/auth/auth-repo.ts +43 -1
  39. package/src/data/sources/cedar/cedar-schema-source.ts +92 -0
  40. package/src/data/sources/cedar/cedar-source.ts +116 -0
  41. package/src/data/sources/oauth/oauth-source.ts +140 -0
  42. package/src/dependencies.ts +16 -7
  43. package/src/domain/authz-types/authz-types-entity.ts +29 -0
  44. package/src/domain/authz-types/use-cases/generate-authz-types-use-case.ts +85 -0
  45. package/src/main.ts +12 -0
@@ -0,0 +1,11 @@
1
+ import type { AuthzSchema } from "../../domain/authz-types/authz-types-entity.js";
2
+ import type { GenerateAuthzTypes } from "../../domain/authz-types/use-cases/generate-authz-types-use-case.js";
3
+ export interface TypesCommandDeps {
4
+ readAuthzSchema(dir: string): AuthzSchema;
5
+ generateAuthzTypes: GenerateAuthzTypes;
6
+ cwd: string;
7
+ log(message: string): void;
8
+ error(message: string): void;
9
+ }
10
+ export declare function typesCommand(argv: string[], deps: TypesCommandDeps): number;
11
+ //# sourceMappingURL=types-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-command.d.ts","sourceRoot":"","sources":["../../../src/app/cli/types-command.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gDAAgD,CAAC;AAClF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qEAAqE,CAAC;AAE9G,MAAM,WAAW,gBAAgB;IAC/B,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAAC;IAC1C,kBAAkB,EAAE,kBAAkB,CAAC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAwBD,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAyB3E"}
@@ -0,0 +1,45 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ const usage = "Usage: insaeng-auth types [--dir authz] [--out src/domain/authz/authz-entity.ts] [--check]";
5
+ function parse(argv) {
6
+ try {
7
+ const { positionals, values } = parseArgs({
8
+ args: argv,
9
+ allowPositionals: true,
10
+ options: {
11
+ dir: { type: "string", default: "authz" },
12
+ out: { type: "string", default: "src/domain/authz/authz-entity.ts" },
13
+ check: { type: "boolean", default: false },
14
+ },
15
+ });
16
+ return positionals.length === 1 && positionals[0] === "types"
17
+ ? values
18
+ : undefined;
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ export function typesCommand(argv, deps) {
25
+ const options = parse(argv);
26
+ if (options === undefined) {
27
+ deps.error(usage);
28
+ return 2;
29
+ }
30
+ const { dir, out, check } = options;
31
+ const path = resolve(deps.cwd, out);
32
+ const text = deps.generateAuthzTypes(deps.readAuthzSchema(resolve(deps.cwd, dir)));
33
+ if (check) {
34
+ if (!existsSync(path) || readFileSync(path, "utf8") !== text) {
35
+ deps.error(`${out} is stale; run insaeng-auth types to regenerate it from ${dir}/schema.cedarschema.`);
36
+ return 1;
37
+ }
38
+ deps.log(`${out} is up to date.`);
39
+ return 0;
40
+ }
41
+ mkdirSync(dirname(path), { recursive: true });
42
+ writeFileSync(path, text);
43
+ deps.log(`Wrote ${out}.`);
44
+ return 0;
45
+ }
@@ -0,0 +1,3 @@
1
+ import type { ErrorHandler } from "hono";
2
+ export declare const authErrorHandler: ErrorHandler;
3
+ //# sourceMappingURL=auth-error-handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-error-handler.d.ts","sourceRoot":"","sources":["../../../src/app/http/auth-error-handler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,YAAY,EAAE,MAAM,MAAM,CAAC;AAwBlD,eAAO,MAAM,gBAAgB,EAAE,YAa9B,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { STATUS_CODES } from "node:http";
2
+ import { Forbidden, Unauthenticated } from "../../domain/auth/auth-entity.js";
3
+ function problem(c, input) {
4
+ const body = {
5
+ type: "about:blank",
6
+ title: STATUS_CODES[input.status] ?? "Error",
7
+ status: input.status,
8
+ detail: input.detail,
9
+ instance: c.req.path,
10
+ };
11
+ return c.body(JSON.stringify(body), input.status, {
12
+ ...input.headers,
13
+ "Content-Type": "application/problem+json",
14
+ });
15
+ }
16
+ export const authErrorHandler = (error, c) => {
17
+ if (error instanceof Forbidden) {
18
+ const action = String(error.action);
19
+ return problem(c, { status: 403, detail: `The caller may not ${action}` });
20
+ }
21
+ if (error instanceof Unauthenticated) {
22
+ return problem(c, {
23
+ status: 401,
24
+ detail: "A valid bearer access token is required",
25
+ headers: { "WWW-Authenticate": "Bearer" },
26
+ });
27
+ }
28
+ throw error;
29
+ };
@@ -0,0 +1,16 @@
1
+ import type { OpenAPIHono } from "@hono/zod-openapi";
2
+ import type { MiddlewareHandler } from "hono";
3
+ import { type Principal, type VerifyAccessToken } from "../../domain/auth/auth-entity.js";
4
+ export { authErrorHandler } from "./auth-error-handler.js";
5
+ export interface AuthEnv {
6
+ Variables: {
7
+ principal: Principal;
8
+ };
9
+ }
10
+ export type OpenAPIApp = Pick<OpenAPIHono, "getOpenAPI31Document">;
11
+ export interface AuthMiddlewareOptions {
12
+ app: OpenAPIApp;
13
+ verifyAccessToken: VerifyAccessToken;
14
+ }
15
+ export declare function createAuthMiddleware({ app, verifyAccessToken, }: AuthMiddlewareOptions): MiddlewareHandler<AuthEnv>;
16
+ //# sourceMappingURL=auth-middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-middleware.d.ts","sourceRoot":"","sources":["../../../src/app/http/auth-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAGvD,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,iBAAiB,EACvB,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,MAAM,WAAW,OAAO;IACtB,SAAS,EAAE;QAAE,SAAS,EAAE,SAAS,CAAA;KAAE,CAAC;CACrC;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,EAAE,sBAAsB,CAAC,CAAC;AAEnE,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,UAAU,CAAC;IAChB,iBAAiB,EAAE,iBAAiB,CAAC;CACtC;AAwDD,wBAAgB,oBAAoB,CAAC,EACnC,GAAG,EACH,iBAAiB,GAClB,EAAE,qBAAqB,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAsBpD"}
@@ -0,0 +1,73 @@
1
+ import { createMiddleware } from "hono/factory";
2
+ import { matchedRoutes } from "hono/route";
3
+ import { Unauthenticated, } from "../../domain/auth/auth-entity.js";
4
+ import { authErrorHandler } from "./auth-error-handler.js";
5
+ export { authErrorHandler } from "./auth-error-handler.js";
6
+ const methods = [
7
+ "get",
8
+ "put",
9
+ "post",
10
+ "delete",
11
+ "options",
12
+ "head",
13
+ "patch",
14
+ "trace",
15
+ ];
16
+ const bearerToken = /^Bearer +(\S+)$/i;
17
+ function routeKey(method, path) {
18
+ return `${method.toUpperCase()} ${path}`;
19
+ }
20
+ function readPublicRoutes(app) {
21
+ const document = app.getOpenAPI31Document({
22
+ openapi: "3.1.0",
23
+ info: { title: "routes", version: "0.0.0" },
24
+ });
25
+ const publicRoutes = new Set();
26
+ const undeclaredRoutes = [];
27
+ for (const [path, item] of Object.entries(document.paths ?? {})) {
28
+ for (const method of methods) {
29
+ const operation = item[method];
30
+ if (operation === undefined) {
31
+ continue;
32
+ }
33
+ if (operation.security === undefined) {
34
+ undeclaredRoutes.push(routeKey(method, path));
35
+ }
36
+ else if (operation.security.length === 0) {
37
+ publicRoutes.add(routeKey(method, path.replaceAll(/\{([^}]+)\}/g, ":$1")));
38
+ }
39
+ }
40
+ }
41
+ if (undeclaredRoutes.length > 0) {
42
+ throw new Error(`Every route must declare security; missing on ${undeclaredRoutes.join(", ")}`);
43
+ }
44
+ return publicRoutes;
45
+ }
46
+ function isPublic(c, publicRoutes) {
47
+ const route = matchedRoutes(c).find(({ method }) => method !== "ALL");
48
+ return (route !== undefined && publicRoutes.has(routeKey(route.method, route.path)));
49
+ }
50
+ export function createAuthMiddleware({ app, verifyAccessToken, }) {
51
+ const publicRoutes = readPublicRoutes(app);
52
+ return createMiddleware(async (c, next) => {
53
+ if (isPublic(c, publicRoutes)) {
54
+ await next();
55
+ return undefined;
56
+ }
57
+ const token = bearerToken.exec(c.req.header("Authorization") ?? "")?.[1];
58
+ if (token === undefined) {
59
+ return authErrorHandler(new Unauthenticated(), c);
60
+ }
61
+ try {
62
+ c.set("principal", await verifyAccessToken(token));
63
+ }
64
+ catch (error) {
65
+ if (error instanceof Unauthenticated) {
66
+ return authErrorHandler(error, c);
67
+ }
68
+ throw error;
69
+ }
70
+ await next();
71
+ return undefined;
72
+ });
73
+ }
@@ -1,7 +1,14 @@
1
1
  import type { AuthRepo } from "../../domain/auth/auth-repo.js";
2
+ import type { CedarSource } from "../sources/cedar/cedar-source.js";
2
3
  import type { JwksSource } from "../sources/jwks/jwks-source.js";
3
4
  export interface AuthRepoDeps {
4
5
  jwks: JwksSource;
6
+ cedar: CedarSource;
5
7
  }
6
- export declare function createAuthRepo({ jwks, }: AuthRepoDeps): Pick<AuthRepo, "findPrincipal">;
8
+ export interface AuthResource {
9
+ type: string;
10
+ id?: string;
11
+ [attribute: string]: unknown;
12
+ }
13
+ export declare function createAuthRepo({ jwks, cedar, }: AuthRepoDeps): AuthRepo<string, AuthResource>;
7
14
  //# sourceMappingURL=auth-repo.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"auth-repo.d.ts","sourceRoot":"","sources":["../../../src/data/auth/auth-repo.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,KAAK,EAGV,WAAW,EACZ,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAEV,UAAU,EACX,MAAM,gCAAgC,CAAC;AAExC,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;CAC9B;AAwCD,wBAAgB,cAAc,CAAC,EAC7B,IAAI,EACJ,KAAK,GACN,EAAE,YAAY,GAAG,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC,CAiC/C"}
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { errors } from "jose";
2
3
  const rejectedTokenErrors = [
3
4
  errors.JWTClaimValidationFailed,
@@ -26,7 +27,10 @@ function toPrincipal(claims) {
26
27
  }
27
28
  return principal;
28
29
  }
29
- export function createAuthRepo({ jwks, }) {
30
+ function toEntity(uid, attrs = {}, parents = []) {
31
+ return { uid, attrs: attrs, parents };
32
+ }
33
+ export function createAuthRepo({ jwks, cedar, }) {
30
34
  return {
31
35
  async findPrincipal(accessToken) {
32
36
  try {
@@ -39,5 +43,23 @@ export function createAuthRepo({ jwks, }) {
39
43
  throw error;
40
44
  }
41
45
  },
46
+ can(principal, action, { type, id = randomUUID(), ...attributes }) {
47
+ const principalUid = {
48
+ type: principal.kind === "client" ? "Client" : "User",
49
+ id: principal.id,
50
+ };
51
+ const roles = principal.roles.map((role) => ({ type: "Role", id: role }));
52
+ const resourceUid = { type, id };
53
+ return Promise.resolve(cedar.isAuthorized({
54
+ principal: principalUid,
55
+ action: { type: "Action", id: action },
56
+ resource: resourceUid,
57
+ entities: [
58
+ toEntity(principalUid, {}, roles),
59
+ ...roles.map((role) => toEntity(role)),
60
+ toEntity(resourceUid, attributes),
61
+ ],
62
+ }));
63
+ },
42
64
  };
43
65
  }
@@ -0,0 +1,3 @@
1
+ import type { AuthzSchema } from "../../../domain/authz-types/authz-types-entity.js";
2
+ export declare function readCedarSchemaSource(dir: string): AuthzSchema;
3
+ //# sourceMappingURL=cedar-schema-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cedar-schema-source.d.ts","sourceRoot":"","sources":["../../../../src/data/sources/cedar/cedar-schema-source.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,WAAW,EAEZ,MAAM,mDAAmD,CAAC;AAqD3D,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CA0B9D"}
@@ -0,0 +1,67 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { schemaToJsonWithResolvedTypes, } from "@cedar-policy/cedar-wasm/nodejs";
4
+ const primitives = {
5
+ String: { kind: "string" },
6
+ Long: { kind: "long" },
7
+ Boolean: { kind: "boolean" },
8
+ Bool: { kind: "boolean" },
9
+ };
10
+ function commonType(json, name) {
11
+ const separator = name.lastIndexOf("::");
12
+ const namespace = separator === -1 ? "" : name.slice(0, separator);
13
+ const id = separator === -1 ? name : name.slice(separator + 2);
14
+ return json[namespace]?.commonTypes?.[id];
15
+ }
16
+ function toType(json, type) {
17
+ if ("element" in type) {
18
+ return { kind: "set", element: toType(json, type.element) };
19
+ }
20
+ if ("attributes" in type) {
21
+ return { kind: "record", attributes: toAttributes(json, type.attributes) };
22
+ }
23
+ if ("name" in type) {
24
+ if (type.type === "Extension") {
25
+ return { kind: "extension", name: type.name };
26
+ }
27
+ const common = commonType(json, type.name);
28
+ return common === undefined
29
+ ? { kind: "entity", name: type.name }
30
+ : toType(json, common);
31
+ }
32
+ const primitive = primitives[type.type.replace(/^__cedar::/, "")];
33
+ if (primitive !== undefined) {
34
+ return primitive;
35
+ }
36
+ const common = commonType(json, type.type);
37
+ return common === undefined
38
+ ? { kind: "extension", name: type.type }
39
+ : toType(json, common);
40
+ }
41
+ function toAttributes(json, attributes) {
42
+ return Object.entries(attributes).map(([name, type]) => ({
43
+ name,
44
+ type: toType(json, type),
45
+ required: type.required !== false,
46
+ }));
47
+ }
48
+ export function readCedarSchemaSource(dir) {
49
+ const answer = schemaToJsonWithResolvedTypes(readFileSync(join(dir, "schema.cedarschema"), "utf8"));
50
+ if (answer.type === "failure") {
51
+ throw new Error(`Invalid Cedar schema in ${dir}:\n${answer.errors.map((error) => `- ${error.message}`).join("\n")}`);
52
+ }
53
+ const { json } = answer;
54
+ return {
55
+ namespaces: Object.entries(json).map(([name, namespace]) => ({
56
+ name,
57
+ actions: Object.keys(namespace.actions),
58
+ entityTypes: Object.entries(namespace.entityTypes).map(([entityName, entityType]) => {
59
+ const shape = "shape" in entityType ? toType(json, entityType.shape) : undefined;
60
+ return {
61
+ name: entityName,
62
+ attributes: shape?.kind === "record" ? shape.attributes : [],
63
+ };
64
+ }),
65
+ })),
66
+ };
67
+ }
@@ -0,0 +1,17 @@
1
+ import { type EntityJson, type TypeAndId } from "@cedar-policy/cedar-wasm/nodejs";
2
+ export type CedarEntityUid = TypeAndId;
3
+ export type CedarEntity = EntityJson;
4
+ export interface CedarSourceOptions {
5
+ dir: string;
6
+ }
7
+ export interface CedarRequest {
8
+ principal: CedarEntityUid;
9
+ action: CedarEntityUid;
10
+ resource: CedarEntityUid;
11
+ entities: CedarEntity[];
12
+ }
13
+ export interface CedarSource {
14
+ isAuthorized(request: CedarRequest): boolean;
15
+ }
16
+ export declare function createCedarSource({ dir }: CedarSourceOptions): CedarSource;
17
+ //# sourceMappingURL=cedar-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cedar-source.d.ts","sourceRoot":"","sources":["../../../../src/data/sources/cedar/cedar-source.ts"],"names":[],"mappings":"AAGA,OAAO,EAOL,KAAK,UAAU,EACf,KAAK,SAAS,EACf,MAAM,iCAAiC,CAAC;AAEzC,MAAM,MAAM,cAAc,GAAG,SAAS,CAAC;AACvC,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC;AAErC,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,cAAc,CAAC;IAC1B,MAAM,EAAE,cAAc,CAAC;IACvB,QAAQ,EAAE,cAAc,CAAC;IACzB,QAAQ,EAAE,WAAW,EAAE,CAAC;CACzB;AAED,MAAM,WAAW,WAAW;IAC1B,YAAY,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC;CAC9C;AAoCD,wBAAgB,iBAAiB,CAAC,EAAE,GAAG,EAAE,EAAE,kBAAkB,GAAG,WAAW,CAiD1E"}
@@ -0,0 +1,75 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { policySetTextToParts, preparsePolicySet, preparseSchema, statefulIsAuthorized, validate, } from "@cedar-policy/cedar-wasm/nodejs";
5
+ function messages(errors, prefix = "") {
6
+ return errors.map((error) => `${prefix}${error.message}`);
7
+ }
8
+ function fail(dir, errors) {
9
+ throw new Error(`Invalid Cedar schema or policies in ${dir}:\n${errors.map((error) => `- ${error}`).join("\n")}`);
10
+ }
11
+ function readPolicies(policiesDir) {
12
+ const policies = {};
13
+ const errors = [];
14
+ const files = readdirSync(policiesDir)
15
+ .filter((file) => file.endsWith(".cedar"))
16
+ .sort();
17
+ for (const file of files) {
18
+ const parts = policySetTextToParts(readFileSync(join(policiesDir, file), "utf8"));
19
+ if (parts.type === "failure") {
20
+ errors.push(...messages(parts.errors, `${file}: `));
21
+ continue;
22
+ }
23
+ if (parts.policy_templates.length > 0) {
24
+ errors.push(`${file}: policy templates are not supported`);
25
+ }
26
+ parts.policies.forEach((policy, index) => {
27
+ policies[`${file}#${String(index)}`] = policy;
28
+ });
29
+ }
30
+ return { policies, errors };
31
+ }
32
+ export function createCedarSource({ dir }) {
33
+ const schema = readFileSync(join(dir, "schema.cedarschema"), "utf8");
34
+ const { policies, errors } = readPolicies(join(dir, "policies"));
35
+ if (errors.length > 0) {
36
+ fail(dir, errors);
37
+ }
38
+ const validation = validate({
39
+ schema,
40
+ policies: { staticPolicies: policies },
41
+ });
42
+ const validationErrors = validation.type === "failure"
43
+ ? validation.errors
44
+ : validation.validationErrors.map(({ error }) => error);
45
+ if (validationErrors.length > 0) {
46
+ fail(dir, messages(validationErrors));
47
+ }
48
+ const id = randomUUID();
49
+ for (const parsed of [
50
+ preparseSchema(id, schema),
51
+ preparsePolicySet(id, { staticPolicies: policies }),
52
+ ]) {
53
+ if (parsed.type === "failure") {
54
+ fail(dir, messages(parsed.errors));
55
+ }
56
+ }
57
+ return {
58
+ isAuthorized({ principal, action, resource, entities }) {
59
+ const answer = statefulIsAuthorized({
60
+ principal,
61
+ action,
62
+ resource,
63
+ context: {},
64
+ entities,
65
+ preparsedSchemaName: id,
66
+ preparsedPolicySetId: id,
67
+ validateRequest: true,
68
+ });
69
+ if (answer.type === "failure") {
70
+ throw new Error(`Cedar authorization failed:\n${messages(answer.errors, "- ").join("\n")}`);
71
+ }
72
+ return answer.response.decision === "allow";
73
+ },
74
+ };
75
+ }
@@ -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
+ }
@@ -1,12 +1,17 @@
1
+ import { type AuthResource } from "./data/auth/auth-repo.js";
1
2
  import { type JwksSourceOptions } from "./data/sources/jwks/jwks-source.js";
2
3
  import type { AuthRepo } from "./domain/auth/auth-repo.js";
4
+ import { assertCanUseCase, type AssertCan } from "./domain/auth/use-cases/assert-can-use-case.js";
3
5
  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 };
6
+ export type { AuthResource, JwksSourceOptions };
7
+ export { assertCanUseCase, verifyAccessTokenUseCase };
8
+ export type AuthOptions = JwksSourceOptions & {
9
+ authzDir: string;
10
+ };
7
11
  export interface Auth {
8
- authRepo: Pick<AuthRepo, "findPrincipal">;
12
+ authRepo: AuthRepo<string, AuthResource>;
9
13
  verifyAccessToken: VerifyAccessToken;
14
+ assertCan: AssertCan<string, AuthResource>;
10
15
  }
11
- export declare function createAuth(options: JwksSourceOptions): Auth;
16
+ export declare function createAuth({ authzDir, ...options }: AuthOptions): Auth;
12
17
  //# sourceMappingURL=dependencies.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"dependencies.d.ts","sourceRoot":"","sources":["../src/dependencies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAE7E,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,gBAAgB,EAChB,KAAK,SAAS,EACf,MAAM,gDAAgD,CAAC;AACxD,OAAO,EACL,wBAAwB,EACxB,KAAK,iBAAiB,EACvB,MAAM,yDAAyD,CAAC;AAEjE,YAAY,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC;AAEtD,MAAM,MAAM,WAAW,GAAG,iBAAiB,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnE,MAAM,WAAW,IAAI;IACnB,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACzC,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,SAAS,EAAE,SAAS,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CAC5C;AAED,wBAAgB,UAAU,CAAC,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,EAAE,WAAW,GAAG,IAAI,CAStE"}
@@ -1,13 +1,16 @@
1
1
  import { createAuthRepo } from "./data/auth/auth-repo.js";
2
+ import { createCedarSource } from "./data/sources/cedar/cedar-source.js";
2
3
  import { createJwksSource, } from "./data/sources/jwks/jwks-source.js";
4
+ import { assertCanUseCase, } from "./domain/auth/use-cases/assert-can-use-case.js";
3
5
  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) {
6
+ export { assertCanUseCase, verifyAccessTokenUseCase };
7
+ export function createAuth({ authzDir, ...options }) {
7
8
  const jwks = createJwksSource(options);
8
- const authRepo = createAuthRepo({ jwks });
9
+ const cedar = createCedarSource({ dir: authzDir });
10
+ const authRepo = createAuthRepo({ jwks, cedar });
9
11
  return {
10
12
  authRepo,
11
13
  verifyAccessToken: verifyAccessTokenUseCase({ authRepo }),
14
+ assertCan: assertCanUseCase({ authRepo }),
12
15
  };
13
16
  }
@@ -0,0 +1,37 @@
1
+ export type AuthzType = {
2
+ kind: "string";
3
+ } | {
4
+ kind: "long";
5
+ } | {
6
+ kind: "boolean";
7
+ } | {
8
+ kind: "set";
9
+ element: AuthzType;
10
+ } | {
11
+ kind: "record";
12
+ attributes: AuthzAttribute[];
13
+ } | {
14
+ kind: "entity";
15
+ name: string;
16
+ } | {
17
+ kind: "extension";
18
+ name: string;
19
+ };
20
+ export interface AuthzAttribute {
21
+ name: string;
22
+ type: AuthzType;
23
+ required: boolean;
24
+ }
25
+ export interface AuthzEntityType {
26
+ name: string;
27
+ attributes: AuthzAttribute[];
28
+ }
29
+ export interface AuthzNamespace {
30
+ name: string;
31
+ entityTypes: AuthzEntityType[];
32
+ actions: string[];
33
+ }
34
+ export interface AuthzSchema {
35
+ namespaces: AuthzNamespace[];
36
+ }
37
+ //# sourceMappingURL=authz-types-entity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authz-types-entity.d.ts","sourceRoot":"","sources":["../../../src/domain/authz-types/authz-types-entity.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,OAAO,EAAE,SAAS,CAAA;CAAE,GACnC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,UAAU,EAAE,cAAc,EAAE,CAAA;CAAE,GAChD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAExC,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,cAAc,EAAE,CAAC;CAC9B;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,eAAe,EAAE,CAAC;IAC/B,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,UAAU,EAAE,cAAc,EAAE,CAAC;CAC9B"}