@abyss-project/main 43.0.0 → 43.1.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 (165) hide show
  1. package/dist/api/index.d.ts +3 -0
  2. package/dist/api/index.js +3 -0
  3. package/dist/api/index.js.map +1 -1
  4. package/dist/api/oauth-application.admin.api.d.ts +2 -0
  5. package/dist/api/oauth-application.admin.api.js +9 -0
  6. package/dist/api/oauth-application.admin.api.js.map +1 -0
  7. package/dist/api/oauth-application.api.d.ts +8 -0
  8. package/dist/api/oauth-application.api.js +30 -0
  9. package/dist/api/oauth-application.api.js.map +1 -0
  10. package/dist/api/oauth-authorization-request.api.d.ts +3 -2
  11. package/dist/api/oauth-authorization-request.api.js +5 -1
  12. package/dist/api/oauth-authorization-request.api.js.map +1 -1
  13. package/dist/api/oauth-grant.api.d.ts +4 -0
  14. package/dist/api/oauth-grant.api.js +15 -0
  15. package/dist/api/oauth-grant.api.js.map +1 -0
  16. package/dist/billing-metric-label/billing-metric-label.labels.d.ts +2 -2
  17. package/dist/billing-metric-label/billing-metric-label.labels.js +2 -2
  18. package/dist/billing-metric-label/billing-metric-label.labels.js.map +1 -1
  19. package/dist/constants/billing-catalog.constants.js +9 -3
  20. package/dist/constants/billing-catalog.constants.js.map +1 -1
  21. package/dist/constants/catalog-plan-quotas.constants.js +8 -11
  22. package/dist/constants/catalog-plan-quotas.constants.js.map +1 -1
  23. package/dist/constants/enforcement-registry.constants.js +6 -6
  24. package/dist/constants/enforcement-registry.constants.js.map +1 -1
  25. package/dist/constants/index.d.ts +2 -0
  26. package/dist/constants/index.js +2 -0
  27. package/dist/constants/index.js.map +1 -1
  28. package/dist/constants/module-catalog.constants.d.ts +1 -0
  29. package/dist/constants/module-catalog.constants.js +10 -0
  30. package/dist/constants/module-catalog.constants.js.map +1 -1
  31. package/dist/constants/oauth-app.constants.d.ts +22 -0
  32. package/dist/constants/oauth-app.constants.js +42 -0
  33. package/dist/constants/oauth-app.constants.js.map +1 -0
  34. package/dist/constants/oauth-scope-catalogue.d.ts +215 -0
  35. package/dist/constants/oauth-scope-catalogue.js +3164 -0
  36. package/dist/constants/oauth-scope-catalogue.js.map +1 -0
  37. package/dist/constants/overage-base-rates.constants.js +0 -1
  38. package/dist/constants/overage-base-rates.constants.js.map +1 -1
  39. package/dist/constants/pack-catalog.constants.js +1 -0
  40. package/dist/constants/pack-catalog.constants.js.map +1 -1
  41. package/dist/constants/public-plans.constants.js +56 -104
  42. package/dist/constants/public-plans.constants.js.map +1 -1
  43. package/dist/constants/quota-metric-kind.constants.js +1 -2
  44. package/dist/constants/quota-metric-kind.constants.js.map +1 -1
  45. package/dist/constants/shared-allowance.constants.js +0 -1
  46. package/dist/constants/shared-allowance.constants.js.map +1 -1
  47. package/dist/constants/tests/billing-catalog.constants.spec.js +0 -47
  48. package/dist/constants/tests/billing-catalog.constants.spec.js.map +1 -1
  49. package/dist/constants/tests/module-catalog.constants.spec.js +1 -1
  50. package/dist/constants/tests/module-catalog.constants.spec.js.map +1 -1
  51. package/dist/constants/tests/oauth-app.constants.spec.d.ts +1 -0
  52. package/dist/constants/tests/oauth-app.constants.spec.js +89 -0
  53. package/dist/constants/tests/oauth-app.constants.spec.js.map +1 -0
  54. package/dist/constants/tests/oauth-scope-catalogue.spec.d.ts +1 -0
  55. package/dist/constants/tests/oauth-scope-catalogue.spec.js +198 -0
  56. package/dist/constants/tests/oauth-scope-catalogue.spec.js.map +1 -0
  57. package/dist/constants/tests/oauth-scope-positions.snapshot.d.ts +39 -0
  58. package/dist/constants/tests/oauth-scope-positions.snapshot.js +225 -0
  59. package/dist/constants/tests/oauth-scope-positions.snapshot.js.map +1 -0
  60. package/dist/constants/tests/pack-catalog.constants.spec.js +1 -1
  61. package/dist/constants/tests/pack-catalog.constants.spec.js.map +1 -1
  62. package/dist/index.d.ts +19 -0
  63. package/dist/index.js +19 -0
  64. package/dist/index.js.map +1 -1
  65. package/dist/permissions/ability.d.ts +1 -1
  66. package/dist/permissions/ability.js +2 -0
  67. package/dist/permissions/ability.js.map +1 -1
  68. package/dist/permissions/tests/ability.spec.js +17 -0
  69. package/dist/permissions/tests/ability.spec.js.map +1 -1
  70. package/dist/server/api-cors.util.d.ts +8 -0
  71. package/dist/server/api-cors.util.js +83 -1
  72. package/dist/server/api-cors.util.js.map +1 -1
  73. package/dist/server/index.d.ts +6 -0
  74. package/dist/server/index.js +6 -0
  75. package/dist/server/index.js.map +1 -1
  76. package/dist/server/oauth-access-token.util.d.ts +30 -0
  77. package/dist/server/oauth-access-token.util.js +116 -0
  78. package/dist/server/oauth-access-token.util.js.map +1 -0
  79. package/dist/server/oauth-claim-format.error.d.ts +4 -0
  80. package/dist/server/oauth-claim-format.error.js +19 -0
  81. package/dist/server/oauth-claim-format.error.js.map +1 -0
  82. package/dist/server/oauth-perimeter-claim.util.d.ts +14 -0
  83. package/dist/server/oauth-perimeter-claim.util.js +109 -0
  84. package/dist/server/oauth-perimeter-claim.util.js.map +1 -0
  85. package/dist/server/oauth-perimeter.util.d.ts +31 -0
  86. package/dist/server/oauth-perimeter.util.js +97 -0
  87. package/dist/server/oauth-perimeter.util.js.map +1 -0
  88. package/dist/server/oauth-route-access.util.d.ts +56 -0
  89. package/dist/server/oauth-route-access.util.js +65 -0
  90. package/dist/server/oauth-route-access.util.js.map +1 -0
  91. package/dist/server/oauth-scope-bits.util.d.ts +9 -0
  92. package/dist/server/oauth-scope-bits.util.js +82 -0
  93. package/dist/server/oauth-scope-bits.util.js.map +1 -0
  94. package/dist/server/tests/api-cors-dynamic.util.spec.d.ts +1 -0
  95. package/dist/server/tests/api-cors-dynamic.util.spec.js +220 -0
  96. package/dist/server/tests/api-cors-dynamic.util.spec.js.map +1 -0
  97. package/dist/server/tests/oauth-access-token.util.spec.d.ts +1 -0
  98. package/dist/server/tests/oauth-access-token.util.spec.js +166 -0
  99. package/dist/server/tests/oauth-access-token.util.spec.js.map +1 -0
  100. package/dist/server/tests/oauth-perimeter-claim.util.spec.d.ts +1 -0
  101. package/dist/server/tests/oauth-perimeter-claim.util.spec.js +148 -0
  102. package/dist/server/tests/oauth-perimeter-claim.util.spec.js.map +1 -0
  103. package/dist/server/tests/oauth-perimeter.util.spec.d.ts +1 -0
  104. package/dist/server/tests/oauth-perimeter.util.spec.js +215 -0
  105. package/dist/server/tests/oauth-perimeter.util.spec.js.map +1 -0
  106. package/dist/server/tests/oauth-route-access.util.spec.d.ts +1 -0
  107. package/dist/server/tests/oauth-route-access.util.spec.js +115 -0
  108. package/dist/server/tests/oauth-route-access.util.spec.js.map +1 -0
  109. package/dist/server/tests/oauth-scope-bits.util.spec.d.ts +1 -0
  110. package/dist/server/tests/oauth-scope-bits.util.spec.js +72 -0
  111. package/dist/server/tests/oauth-scope-bits.util.spec.js.map +1 -0
  112. package/dist/types/enum/api-error.enum.d.ts +1 -0
  113. package/dist/types/enum/api-error.enum.js +1 -0
  114. package/dist/types/enum/api-error.enum.js.map +1 -1
  115. package/dist/types/enum/index.d.ts +2 -0
  116. package/dist/types/enum/index.js +2 -0
  117. package/dist/types/enum/index.js.map +1 -1
  118. package/dist/types/enum/oauth-app.enum.d.ts +38 -0
  119. package/dist/types/enum/oauth-app.enum.js +47 -0
  120. package/dist/types/enum/oauth-app.enum.js.map +1 -0
  121. package/dist/types/enum/oauth-scope.enum.d.ts +74 -0
  122. package/dist/types/enum/oauth-scope.enum.js +86 -0
  123. package/dist/types/enum/oauth-scope.enum.js.map +1 -0
  124. package/dist/types/enum/organization-billing.enum.d.ts +1 -1
  125. package/dist/types/enum/organization-billing.enum.js +1 -1
  126. package/dist/types/enum/organization-billing.enum.js.map +1 -1
  127. package/dist/types/enum/project-access-permission.enum.d.ts +2 -1
  128. package/dist/types/enum/project-access-permission.enum.js +1 -0
  129. package/dist/types/enum/project-access-permission.enum.js.map +1 -1
  130. package/dist/types/interface/api/index.d.ts +5 -0
  131. package/dist/types/interface/api/index.js +5 -0
  132. package/dist/types/interface/api/index.js.map +1 -1
  133. package/dist/types/interface/api/requests/index.d.ts +3 -0
  134. package/dist/types/interface/api/requests/index.js +3 -0
  135. package/dist/types/interface/api/requests/index.js.map +1 -1
  136. package/dist/types/interface/api/requests/oauth-application.request.d.ts +34 -0
  137. package/dist/types/interface/api/requests/oauth-application.request.js +3 -0
  138. package/dist/types/interface/api/requests/oauth-application.request.js.map +1 -0
  139. package/dist/types/interface/api/requests/oauth-authorization-request.request.d.ts +3 -0
  140. package/dist/types/interface/api/requests/oauth-grant.request.d.ts +3 -0
  141. package/dist/types/interface/api/requests/oauth-grant.request.js +3 -0
  142. package/dist/types/interface/api/requests/oauth-grant.request.js.map +1 -0
  143. package/dist/types/interface/api/requests/oauth-perimeter.request.d.ts +30 -0
  144. package/dist/types/interface/api/requests/oauth-perimeter.request.js +5 -0
  145. package/dist/types/interface/api/requests/oauth-perimeter.request.js.map +1 -0
  146. package/dist/types/interface/api/responses/index.d.ts +4 -0
  147. package/dist/types/interface/api/responses/index.js +4 -0
  148. package/dist/types/interface/api/responses/index.js.map +1 -1
  149. package/dist/types/interface/api/responses/oauth-application.response.d.ts +43 -0
  150. package/dist/types/interface/api/responses/oauth-application.response.js +3 -0
  151. package/dist/types/interface/api/responses/oauth-application.response.js.map +1 -0
  152. package/dist/types/interface/api/responses/oauth-authorization-request.response.d.ts +24 -2
  153. package/dist/types/interface/api/responses/oauth-grant.response.d.ts +19 -0
  154. package/dist/types/interface/api/responses/oauth-grant.response.js +3 -0
  155. package/dist/types/interface/api/responses/oauth-grant.response.js.map +1 -0
  156. package/dist/types/interface/api/responses/oauth-perimeter.response.d.ts +23 -0
  157. package/dist/types/interface/api/responses/oauth-perimeter.response.js +3 -0
  158. package/dist/types/interface/api/responses/oauth-perimeter.response.js.map +1 -0
  159. package/dist/types/interface/api/responses/oauth-userinfo.response.d.ts +8 -0
  160. package/dist/types/interface/api/responses/oauth-userinfo.response.js +3 -0
  161. package/dist/types/interface/api/responses/oauth-userinfo.response.js.map +1 -0
  162. package/dist/types/interface/api/responses/organization-billing.response.d.ts +1 -0
  163. package/dist/types/interface/api/responses/user-billing.response.d.ts +1 -0
  164. package/dist/types/interface/mcp/mcp-oauth.d.ts +2 -0
  165. package/package.json +17 -10
@@ -0,0 +1,56 @@
1
+ import { OAuthScopeName } from '../constants/oauth-scope-catalogue';
2
+ import type { OAuthRoutePerimeter } from '../types/enum/oauth-scope.enum';
3
+ import type { OAuthAccessTokenClaims } from './oauth-access-token.util';
4
+ import type { OAuthPerimeterEntries } from './oauth-perimeter-claim.util';
5
+ export type AppTokenRoute = {
6
+ kind: 'scope';
7
+ scope: string;
8
+ perimeter: `${OAuthRoutePerimeter}`;
9
+ resources: 1 | 2;
10
+ } | {
11
+ kind: 'refused';
12
+ reason: string;
13
+ };
14
+ export interface OAuthAppRequestContext {
15
+ clientId: string;
16
+ userId: string;
17
+ scopes: readonly OAuthScopeName[];
18
+ perimeter: OAuthPerimeterEntries;
19
+ }
20
+ export interface OAuthAppLocals {
21
+ oauth?: OAuthAppRequestContext | null;
22
+ oauthPerimeterApplied?: number;
23
+ }
24
+ export declare const oauthAppRequestContextOf: (claims: OAuthAccessTokenClaims) => OAuthAppRequestContext;
25
+ export declare const isOAuthAppRequest: (locals: OAuthAppLocals) => locals is OAuthAppLocals & {
26
+ oauth: OAuthAppRequestContext;
27
+ };
28
+ export declare enum OAuthGuardRefusalCode {
29
+ INSUFFICIENT_SCOPE = "insufficient_scope",
30
+ OAUTH_TOKEN_NOT_ALLOWED = "oauthTokenNotAllowed",
31
+ OAUTH_RESOURCE_NOT_GRANTED = "oauthResourceNotGranted"
32
+ }
33
+ export declare const insufficientScopeChallenge: (scope: string) => string;
34
+ export type OAuthGuardOutcome = {
35
+ allowed: true;
36
+ } | {
37
+ allowed: false;
38
+ status: 403;
39
+ code: OAuthGuardRefusalCode.INSUFFICIENT_SCOPE;
40
+ requiredScope: string;
41
+ wwwAuthenticate: string;
42
+ } | {
43
+ allowed: false;
44
+ status: 403;
45
+ code: OAuthGuardRefusalCode.OAUTH_TOKEN_NOT_ALLOWED;
46
+ };
47
+ export declare const checkOAuthRouteAccess: (appTokenRoute: AppTokenRoute | undefined, claims: Pick<OAuthAccessTokenClaims, "scopes">) => OAuthGuardOutcome;
48
+ export declare class OAuthAppRefusalError extends Error {
49
+ readonly code: OAuthGuardRefusalCode;
50
+ readonly requiredScope?: string | undefined;
51
+ readonly status = 403;
52
+ constructor(code: OAuthGuardRefusalCode, requiredScope?: string | undefined);
53
+ get wwwAuthenticate(): string | undefined;
54
+ }
55
+ export declare const requireOAuthScope: (locals: OAuthAppLocals, scope: OAuthScopeName) => void;
56
+ export declare const refuseFieldForOAuthApp: (locals: OAuthAppLocals, present: boolean) => void;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.refuseFieldForOAuthApp = exports.requireOAuthScope = exports.OAuthAppRefusalError = exports.checkOAuthRouteAccess = exports.insufficientScopeChallenge = exports.OAuthGuardRefusalCode = exports.isOAuthAppRequest = exports.oauthAppRequestContextOf = void 0;
4
+ const oauthAppRequestContextOf = (claims) => ({
5
+ clientId: claims.clientId,
6
+ userId: claims.sub,
7
+ scopes: claims.scopes,
8
+ perimeter: claims.perimeter,
9
+ });
10
+ exports.oauthAppRequestContextOf = oauthAppRequestContextOf;
11
+ const isOAuthAppRequest = (locals) => locals.oauth !== undefined && locals.oauth !== null;
12
+ exports.isOAuthAppRequest = isOAuthAppRequest;
13
+ var OAuthGuardRefusalCode;
14
+ (function (OAuthGuardRefusalCode) {
15
+ OAuthGuardRefusalCode["INSUFFICIENT_SCOPE"] = "insufficient_scope";
16
+ OAuthGuardRefusalCode["OAUTH_TOKEN_NOT_ALLOWED"] = "oauthTokenNotAllowed";
17
+ OAuthGuardRefusalCode["OAUTH_RESOURCE_NOT_GRANTED"] = "oauthResourceNotGranted";
18
+ })(OAuthGuardRefusalCode || (exports.OAuthGuardRefusalCode = OAuthGuardRefusalCode = {}));
19
+ const insufficientScopeChallenge = (scope) => `Bearer error="insufficient_scope", scope="${scope}"`;
20
+ exports.insufficientScopeChallenge = insufficientScopeChallenge;
21
+ const checkOAuthRouteAccess = (appTokenRoute, claims) => {
22
+ if (appTokenRoute === undefined || appTokenRoute.kind !== 'scope') {
23
+ return { allowed: false, status: 403, code: OAuthGuardRefusalCode.OAUTH_TOKEN_NOT_ALLOWED };
24
+ }
25
+ const granted = claims.scopes;
26
+ if (!granted.includes(appTokenRoute.scope)) {
27
+ return {
28
+ allowed: false,
29
+ status: 403,
30
+ code: OAuthGuardRefusalCode.INSUFFICIENT_SCOPE,
31
+ requiredScope: appTokenRoute.scope,
32
+ wwwAuthenticate: (0, exports.insufficientScopeChallenge)(appTokenRoute.scope),
33
+ };
34
+ }
35
+ return { allowed: true };
36
+ };
37
+ exports.checkOAuthRouteAccess = checkOAuthRouteAccess;
38
+ class OAuthAppRefusalError extends Error {
39
+ constructor(code, requiredScope) {
40
+ super(requiredScope === undefined ? code : `${code}: ${requiredScope}`);
41
+ this.code = code;
42
+ this.requiredScope = requiredScope;
43
+ this.status = 403;
44
+ this.name = 'OAuthAppRefusalError';
45
+ }
46
+ get wwwAuthenticate() {
47
+ return this.requiredScope === undefined
48
+ ? undefined
49
+ : (0, exports.insufficientScopeChallenge)(this.requiredScope);
50
+ }
51
+ }
52
+ exports.OAuthAppRefusalError = OAuthAppRefusalError;
53
+ const requireOAuthScope = (locals, scope) => {
54
+ if ((0, exports.isOAuthAppRequest)(locals) && !locals.oauth.scopes.includes(scope)) {
55
+ throw new OAuthAppRefusalError(OAuthGuardRefusalCode.INSUFFICIENT_SCOPE, scope);
56
+ }
57
+ };
58
+ exports.requireOAuthScope = requireOAuthScope;
59
+ const refuseFieldForOAuthApp = (locals, present) => {
60
+ if (present && (0, exports.isOAuthAppRequest)(locals)) {
61
+ throw new OAuthAppRefusalError(OAuthGuardRefusalCode.OAUTH_TOKEN_NOT_ALLOWED);
62
+ }
63
+ };
64
+ exports.refuseFieldForOAuthApp = refuseFieldForOAuthApp;
65
+ //# sourceMappingURL=oauth-route-access.util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-route-access.util.js","sourceRoot":"","sources":["../../src/server/oauth-route-access.util.ts"],"names":[],"mappings":";;;AAkDO,MAAM,wBAAwB,GAAG,CACtC,MAA8B,EACN,EAAE,CAAC,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC,QAAQ;IACzB,MAAM,EAAE,MAAM,CAAC,GAAG;IAClB,MAAM,EAAE,MAAM,CAAC,MAAM;IACrB,SAAS,EAAE,MAAM,CAAC,SAAS;CAC5B,CAAC,CAAC;AAPU,QAAA,wBAAwB,4BAOlC;AAGI,MAAM,iBAAiB,GAAG,CAC/B,MAAsB,EACwC,EAAE,CAChE,MAAM,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,CAAC;AAHzC,QAAA,iBAAiB,qBAGwB;AAEtD,IAAY,qBAOX;AAPD,WAAY,qBAAqB;IAE/B,kEAAyC,CAAA;IAEzC,yEAAgD,CAAA;IAEhD,+EAAsD,CAAA;AACxD,CAAC,EAPW,qBAAqB,qCAArB,qBAAqB,QAOhC;AAGM,MAAM,0BAA0B,GAAG,CAAC,KAAa,EAAU,EAAE,CAClE,6CAA6C,KAAK,GAAG,CAAC;AAD3C,QAAA,0BAA0B,8BACiB;AAmBjD,MAAM,qBAAqB,GAAG,CACnC,aAAwC,EACxC,MAA8C,EAC3B,EAAE;IACrB,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QAClE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,qBAAqB,CAAC,uBAAuB,EAAE,CAAC;IAC9F,CAAC;IACD,MAAM,OAAO,GAAsB,MAAM,CAAC,MAAM,CAAC;IACjD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3C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AQ,EAAE;IACvF,IAAI,OAAO,IAAI,IAAA,yBAAiB,EAAC,MAAM,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,oBAAoB,CAAC,qBAAqB,CAAC,uBAAuB,CAAC,CAAC;IAChF,CAAC;AACH,CAAC,CAAC;AAJW,QAAA,sBAAsB,0BAIjC"}
@@ -0,0 +1,9 @@
1
+ import { OAuthScopeName } from '../constants/oauth-scope-catalogue';
2
+ import { OAuthService } from '../types/enum/oauth-scope.enum';
3
+ export declare const OAUTH_SCOPE_CLAIM = "abyss_scp";
4
+ export interface OAuthScopeClaim {
5
+ v: number;
6
+ s: Partial<Record<OAuthService, string>>;
7
+ }
8
+ export declare const encodeOAuthScopes: (scopes: readonly OAuthScopeName[]) => OAuthScopeClaim;
9
+ export declare const decodeOAuthScopes: (claim: unknown) => OAuthScopeName[];
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeOAuthScopes = exports.encodeOAuthScopes = exports.OAUTH_SCOPE_CLAIM = void 0;
4
+ const oauth_scope_catalogue_1 = require("../constants/oauth-scope-catalogue");
5
+ const oauth_scope_enum_1 = require("../types/enum/oauth-scope.enum");
6
+ const oauth_claim_format_error_1 = require("./oauth-claim-format.error");
7
+ exports.OAUTH_SCOPE_CLAIM = 'abyss_scp';
8
+ const SERVICES = new Set(Object.values(oauth_scope_enum_1.OAuthService));
9
+ const isService = (value) => SERVICES.has(value);
10
+ const SCOPE_AT = (() => {
11
+ const byService = new Map();
12
+ for (const service of Object.values(oauth_scope_enum_1.OAuthService)) {
13
+ byService.set(service, new Map());
14
+ }
15
+ for (const scope of Object.values(oauth_scope_catalogue_1.OAuthScopeName)) {
16
+ const definition = oauth_scope_catalogue_1.OAUTH_SCOPE_CATALOGUE[scope];
17
+ byService.get(definition.service)?.set(definition.bit, scope);
18
+ }
19
+ return byService;
20
+ })();
21
+ const PUBLISHED_BYTES = new Map(Object.values(oauth_scope_enum_1.OAuthService).map((service) => {
22
+ const positions = [
23
+ ...(SCOPE_AT.get(service)?.keys() ?? []),
24
+ ...oauth_scope_catalogue_1.OAUTH_SCOPE_RETIRED_BITS[service],
25
+ ];
26
+ const highest = positions.length === 0 ? -1 : Math.max(...positions);
27
+ return [service, Math.ceil((highest + 1) / 8)];
28
+ }));
29
+ const encodeOAuthScopes = (scopes) => {
30
+ const bitsByService = new Map();
31
+ for (const scope of scopes) {
32
+ const { service, bit } = oauth_scope_catalogue_1.OAUTH_SCOPE_CATALOGUE[scope];
33
+ bitsByService.set(service, [...(bitsByService.get(service) ?? []), bit]);
34
+ }
35
+ const s = {};
36
+ for (const [service, bits] of bitsByService) {
37
+ const bytes = Buffer.alloc(Math.floor(Math.max(...bits) / 8) + 1);
38
+ for (const bit of bits) {
39
+ bytes[bit >> 3] |= 1 << (bit & 7);
40
+ }
41
+ s[service] = bytes.toString('base64url');
42
+ }
43
+ return { v: oauth_scope_catalogue_1.OAUTH_SCOPE_CATALOGUE_VERSION, s };
44
+ };
45
+ exports.encodeOAuthScopes = encodeOAuthScopes;
46
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
47
+ const decodeOAuthScopes = (claim) => {
48
+ if (!isRecord(claim) || !Number.isInteger(claim.v) || !isRecord(claim.s)) {
49
+ throw new oauth_claim_format_error_1.OAuthClaimFormatError(`${exports.OAUTH_SCOPE_CLAIM} is not { v, s }`);
50
+ }
51
+ const newer = Number(claim.v) > oauth_scope_catalogue_1.OAUTH_SCOPE_CATALOGUE_VERSION;
52
+ const scopes = [];
53
+ for (const [service, field] of Object.entries(claim.s)) {
54
+ if (typeof field !== 'string') {
55
+ throw new oauth_claim_format_error_1.OAuthClaimFormatError(`${exports.OAUTH_SCOPE_CLAIM}.s.${service} is not a string`);
56
+ }
57
+ const bytes = (0, oauth_claim_format_error_1.decodeBase64Url)(field, `${exports.OAUTH_SCOPE_CLAIM}.s.${service}`);
58
+ if (!isService(service)) {
59
+ if (newer) {
60
+ continue;
61
+ }
62
+ throw new oauth_claim_format_error_1.OAuthClaimFormatError(`${exports.OAUTH_SCOPE_CLAIM}.s names an unknown service ${service}`);
63
+ }
64
+ if (!newer && bytes.length > (PUBLISHED_BYTES.get(service) ?? 0)) {
65
+ throw new oauth_claim_format_error_1.OAuthClaimFormatError(`${exports.OAUTH_SCOPE_CLAIM}.s.${service} is longer than its positions`);
66
+ }
67
+ const scopeAt = SCOPE_AT.get(service);
68
+ bytes.forEach((byte, index) => {
69
+ for (let offset = 0; offset < 8; offset += 1) {
70
+ if ((byte & (1 << offset)) !== 0) {
71
+ const scope = scopeAt?.get(index * 8 + offset);
72
+ if (scope !== undefined) {
73
+ scopes.push(scope);
74
+ }
75
+ }
76
+ }
77
+ });
78
+ }
79
+ return scopes;
80
+ };
81
+ exports.decodeOAuthScopes = decodeOAuthScopes;
82
+ //# sourceMappingURL=oauth-scope-bits.util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-scope-bits.util.js","sourceRoot":"","sources":["../../src/server/oauth-scope-bits.util.ts"],"names":[],"mappings":";;;AAUA,8EAK4C;AAC5C,qEAA8D;AAC9D,yEAAoF;AAGvE,QAAA,iBAAiB,GAAG,WAAW,CAAC;AAQ7C,MAAM,QAAQ,GAAwB,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,+BAAY,CAAC,CAAC,CAAC;AAE3E,MAAM,SAAS,GAAG,CAAC,KAAa,EAAyB,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAGhF,MAAM,QAAQ,GAAmE,CAAC,GAAG,EAAE;IACrF,MAAM,SAAS,GAAG,IAAI,GAAG,EAA6C,CAAC;IACvE,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,+BAAY,CAAC,EAAE,CAAC;QAClD,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;IACpC,CAAC;IACD,KAAK,MAAM,KAAK,IAA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AM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;oBACrB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAnCW,QAAA,iBAAiB,qBAmC5B"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const api_cors_util_1 = require("../api-cors.util");
4
+ const FRONT = 'https://app.abyss-project.fr';
5
+ const APP_ORIGIN = 'https://app.example.com';
6
+ const OTHER_APP_ORIGIN = 'https://other.example.com';
7
+ const POLICY = {
8
+ allowedOrigins: [FRONT, 'https://*.abysspage.com'],
9
+ allowedHeaders: ['authorization', 'X-Abyss-Locale'],
10
+ exposedHeaders: ['Content-disposition'],
11
+ };
12
+ const optionsFor = (delegate, origin) => new Promise((resolve, reject) => {
13
+ delegate({ headers: { origin } }, (err, options) => {
14
+ if (err || !options) {
15
+ reject(err ?? new Error('no options'));
16
+ return;
17
+ }
18
+ resolve(options);
19
+ });
20
+ });
21
+ const deferred = () => {
22
+ let resolve = () => undefined;
23
+ let reject = () => undefined;
24
+ const promise = new Promise((res, rej) => {
25
+ resolve = res;
26
+ reject = rej;
27
+ });
28
+ return { promise, resolve, reject };
29
+ };
30
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
31
+ const delegateWith = (thirdParty) => {
32
+ let clock = 1_000_000;
33
+ const loadOrigins = jest.fn(thirdParty.loadOrigins ?? (() => Promise.resolve([APP_ORIGIN])));
34
+ const onLoadError = jest.fn();
35
+ const delegate = (0, api_cors_util_1.createDynamicApiCorsOptionsDelegate)(POLICY, {
36
+ ...thirdParty,
37
+ loadOrigins,
38
+ onLoadError,
39
+ now: () => clock,
40
+ });
41
+ return {
42
+ delegate,
43
+ loadOrigins,
44
+ onLoadError,
45
+ advance: (ms) => {
46
+ clock += ms;
47
+ },
48
+ };
49
+ };
50
+ describe('createDynamicApiCorsOptionsDelegate (CA22)', () => {
51
+ it('gives credentials to an origin of the fixed list, without reading the app origins', async () => {
52
+ const { delegate, loadOrigins } = delegateWith({});
53
+ await expect(optionsFor(delegate, FRONT)).resolves.toEqual({
54
+ origin: true,
55
+ credentials: true,
56
+ allowedHeaders: ['authorization', 'X-Abyss-Locale'],
57
+ exposedHeaders: ['Content-disposition'],
58
+ });
59
+ await expect(optionsFor(delegate, 'https://memories.abysspage.com')).resolves.toMatchObject({
60
+ origin: true,
61
+ credentials: true,
62
+ });
63
+ expect(loadOrigins).not.toHaveBeenCalled();
64
+ });
65
+ it('gives credentials to a native app origin', async () => {
66
+ const { delegate } = delegateWith({});
67
+ await expect(optionsFor(delegate, 'capacitor://localhost')).resolves.toMatchObject({
68
+ origin: true,
69
+ credentials: true,
70
+ });
71
+ });
72
+ it('gives CORS without credentials to an app origin, Authorization and Content-Type allowed', async () => {
73
+ const { delegate } = delegateWith({});
74
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toEqual({
75
+ origin: true,
76
+ credentials: false,
77
+ allowedHeaders: ['authorization', 'X-Abyss-Locale', 'Content-Type'],
78
+ exposedHeaders: ['Content-disposition'],
79
+ });
80
+ });
81
+ it('matches an app origin after normalization (case, default port)', async () => {
82
+ const { delegate } = delegateWith({
83
+ loadOrigins: () => Promise.resolve(['https://App.Example.com:443', 'http://localhost:5173']),
84
+ });
85
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: true });
86
+ await expect(optionsFor(delegate, 'http://localhost:5173')).resolves.toMatchObject({
87
+ origin: true,
88
+ credentials: false,
89
+ });
90
+ await expect(optionsFor(delegate, 'http://localhost:5174')).resolves.toMatchObject({
91
+ origin: false,
92
+ });
93
+ });
94
+ it('gives nothing to an unknown origin, nor to a request without Origin', async () => {
95
+ const { delegate } = delegateWith({});
96
+ await expect(optionsFor(delegate, 'https://evil.example.com')).resolves.toEqual({
97
+ origin: false,
98
+ credentials: false,
99
+ allowedHeaders: ['authorization', 'X-Abyss-Locale'],
100
+ exposedHeaders: ['Content-disposition'],
101
+ });
102
+ await expect(optionsFor(delegate, undefined)).resolves.toMatchObject({
103
+ origin: false,
104
+ credentials: false,
105
+ });
106
+ });
107
+ it('ignores a declared origin that is not a plain origin, never an error', async () => {
108
+ const { delegate, onLoadError } = delegateWith({
109
+ loadOrigins: () => Promise.resolve([
110
+ 'https://*.example.com',
111
+ 'https://app.example.com/path',
112
+ 'not an origin',
113
+ 'https://other.example.com',
114
+ ]),
115
+ });
116
+ await expect(optionsFor(delegate, 'https://sub.example.com')).resolves.toMatchObject({
117
+ origin: false,
118
+ });
119
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: false });
120
+ await expect(optionsFor(delegate, OTHER_APP_ORIGIN)).resolves.toMatchObject({ origin: true });
121
+ expect(onLoadError).not.toHaveBeenCalled();
122
+ });
123
+ it('reads once while concurrent requests wait for the first read', async () => {
124
+ const read = deferred();
125
+ const { delegate, loadOrigins } = delegateWith({ loadOrigins: () => read.promise });
126
+ const answers = Promise.all([
127
+ optionsFor(delegate, APP_ORIGIN),
128
+ optionsFor(delegate, APP_ORIGIN),
129
+ optionsFor(delegate, 'https://evil.example.com'),
130
+ ]);
131
+ await flush();
132
+ expect(loadOrigins).toHaveBeenCalledTimes(1);
133
+ read.resolve([APP_ORIGIN]);
134
+ const [first, second, unknown] = await answers;
135
+ expect(first.origin).toBe(true);
136
+ expect(second.origin).toBe(true);
137
+ expect(unknown.origin).toBe(false);
138
+ expect(loadOrigins).toHaveBeenCalledTimes(1);
139
+ });
140
+ it('serves the cached list within the TTL, then serves the stale list while it reads again', async () => {
141
+ const second = deferred();
142
+ let calls = 0;
143
+ const { delegate, loadOrigins, advance } = delegateWith({
144
+ loadOrigins: () => {
145
+ calls += 1;
146
+ return calls === 1 ? Promise.resolve([APP_ORIGIN]) : second.promise;
147
+ },
148
+ });
149
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: true });
150
+ advance(api_cors_util_1.API_CORS_THIRD_PARTY_ORIGINS_TTL_MS - 1);
151
+ await expect(optionsFor(delegate, OTHER_APP_ORIGIN)).resolves.toMatchObject({ origin: false });
152
+ expect(loadOrigins).toHaveBeenCalledTimes(1);
153
+ advance(1);
154
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: true });
155
+ await expect(optionsFor(delegate, OTHER_APP_ORIGIN)).resolves.toMatchObject({ origin: false });
156
+ expect(loadOrigins).toHaveBeenCalledTimes(2);
157
+ second.resolve([OTHER_APP_ORIGIN]);
158
+ await flush();
159
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: false });
160
+ await expect(optionsFor(delegate, OTHER_APP_ORIGIN)).resolves.toMatchObject({ origin: true });
161
+ expect(loadOrigins).toHaveBeenCalledTimes(2);
162
+ });
163
+ it('honours a custom ttlMs', async () => {
164
+ const { delegate, loadOrigins, advance } = delegateWith({ ttlMs: 10 });
165
+ await optionsFor(delegate, APP_ORIGIN);
166
+ advance(10);
167
+ await optionsFor(delegate, APP_ORIGIN);
168
+ await flush();
169
+ expect(loadOrigins).toHaveBeenCalledTimes(2);
170
+ });
171
+ it('keeps the last list when a read fails, reports the error, and retries after the TTL', async () => {
172
+ const failure = new Error('abyss-main unreachable');
173
+ let calls = 0;
174
+ const { delegate, loadOrigins, onLoadError, advance } = delegateWith({
175
+ loadOrigins: () => {
176
+ calls += 1;
177
+ return calls === 2 ? Promise.reject(failure) : Promise.resolve([APP_ORIGIN]);
178
+ },
179
+ });
180
+ await optionsFor(delegate, APP_ORIGIN);
181
+ advance(api_cors_util_1.API_CORS_THIRD_PARTY_ORIGINS_TTL_MS);
182
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: true });
183
+ await flush();
184
+ expect(onLoadError).toHaveBeenCalledWith(failure);
185
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: true });
186
+ expect(loadOrigins).toHaveBeenCalledTimes(2);
187
+ advance(api_cors_util_1.API_CORS_THIRD_PARTY_ORIGINS_TTL_MS);
188
+ await optionsFor(delegate, APP_ORIGIN);
189
+ await flush();
190
+ expect(loadOrigins).toHaveBeenCalledTimes(3);
191
+ });
192
+ it('serves an empty list before any successful read', async () => {
193
+ const failure = new Error('down');
194
+ const { delegate, onLoadError } = delegateWith({
195
+ loadOrigins: () => Promise.reject(failure),
196
+ });
197
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: false });
198
+ expect(onLoadError).toHaveBeenCalledWith(failure);
199
+ await expect(optionsFor(delegate, FRONT)).resolves.toMatchObject({ credentials: true });
200
+ });
201
+ it('survives a loader that throws synchronously and an onLoadError that throws', async () => {
202
+ let calls = 0;
203
+ const delegate = (0, api_cors_util_1.createDynamicApiCorsOptionsDelegate)(POLICY, {
204
+ loadOrigins: () => {
205
+ calls += 1;
206
+ throw new Error('sync failure');
207
+ },
208
+ onLoadError: () => {
209
+ throw new Error('logger failure');
210
+ },
211
+ ttlMs: 0,
212
+ });
213
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: false });
214
+ await flush();
215
+ await expect(optionsFor(delegate, APP_ORIGIN)).resolves.toMatchObject({ origin: false });
216
+ await flush();
217
+ expect(calls).toBeGreaterThanOrEqual(2);
218
+ });
219
+ });
220
+ //# sourceMappingURL=api-cors-dynamic.util.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-cors-dynamic.util.spec.js","sourceRoot":"","sources":["../../../src/server/tests/api-cors-dynamic.util.spec.ts"],"names":[],"mappings":";;AAAA,oDAM0B;AAE1B,MAAM,KAAK,GAAG,8BAA8B,CAAC;AAC7C,MAAM,UAAU,GAAG,yBAAyB,CAAC;AAC7C,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAErD,MAAM,MAAM,GAAG;IACb,cAAc,EAAE,CAAC,KAAK,EAAE,yBAAyB,CAAC;IAClD,c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
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const crypto_1 = require("crypto");
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const oauth_scope_catalogue_1 = require("../../constants/oauth-scope-catalogue");
9
+ const oauth_app_enum_1 = require("../../types/enum/oauth-app.enum");
10
+ const oauth_scope_enum_1 = require("../../types/enum/oauth-scope.enum");
11
+ const oauth_access_token_util_1 = require("../oauth-access-token.util");
12
+ const oauth_perimeter_claim_util_1 = require("../oauth-perimeter-claim.util");
13
+ const oauth_scope_bits_util_1 = require("../oauth-scope-bits.util");
14
+ const SPACE_ID = '0f8c2a3e-9b1d-4c6e-8a2f-5d7e9b1c3a4f';
15
+ const keyPair = () => (0, crypto_1.generateKeyPairSync)('rsa', {
16
+ modulusLength: 2048,
17
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
18
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
19
+ });
20
+ const { publicKey, privateKey } = keyPair();
21
+ const other = keyPair();
22
+ const base64url = (value) => Buffer.from(value).toString('base64url');
23
+ const encode = (header, payload) => `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`;
24
+ const signRs256 = (header, payload, key = privateKey) => {
25
+ const input = encode({ alg: 'RS256', ...header }, payload);
26
+ const signature = (0, crypto_1.createSign)('RSA-SHA256').update(input).sign(key);
27
+ return `${input}.${base64url(signature)}`;
28
+ };
29
+ const nowSeconds = () => Math.floor(Date.now() / 1000);
30
+ const appPayload = (overrides = {}) => ({
31
+ iss: 'https://api.abyss-project.fr',
32
+ sub: 'user-1',
33
+ aud: [oauth_app_enum_1.OAuthAudience.ABYSS_CLOUD, oauth_app_enum_1.OAuthAudience.ABYSS_MAIN],
34
+ client_id: 'abys_app_client',
35
+ abyss_scp: (0, oauth_scope_bits_util_1.encodeOAuthScopes)([oauth_scope_catalogue_1.OAuthScopeName.CLOUD_FILE_READ, oauth_scope_catalogue_1.OAuthScopeName.PROFILE]),
36
+ abyss_perimeter: (0, oauth_perimeter_claim_util_1.encodeOAuthPerimeter)([
37
+ { service: oauth_scope_enum_1.OAuthService.CLOUD, unit: oauth_scope_enum_1.OAuthPerimeterUnit.SPACE, id: SPACE_ID },
38
+ ]),
39
+ jti: 'jti-1',
40
+ iat: nowSeconds(),
41
+ exp: nowSeconds() + 900,
42
+ ...overrides,
43
+ });
44
+ const AT_JWT = { typ: 'at+jwt' };
45
+ const appToken = (overrides = {}) => signRs256(AT_JWT, appPayload(overrides));
46
+ const sessionToken = () => jsonwebtoken_1.default.sign({ UUID: 'user-1', sid: 'session-1' }, privateKey, {
47
+ algorithm: 'RS256',
48
+ expiresIn: 900,
49
+ });
50
+ const verifyFor = (token, audience = oauth_app_enum_1.OAuthAudience.ABYSS_CLOUD) => (0, oauth_access_token_util_1.verifyOAuthAccessToken)(token, { publicKey, audience });
51
+ const reasonOf = (token, audience) => {
52
+ try {
53
+ verifyFor(token, audience);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof oauth_access_token_util_1.OAuthAccessTokenError) {
57
+ return error.reason;
58
+ }
59
+ throw error;
60
+ }
61
+ throw new Error('the token was accepted');
62
+ };
63
+ describe('oauth-access-token.util', () => {
64
+ describe('verifyOAuthAccessToken (CA17)', () => {
65
+ it('accepts a valid RS256 at+jwt whose aud holds the audience, and reads its claims', () => {
66
+ const exp = nowSeconds() + 900;
67
+ const claims = verifyFor(appToken({ exp }));
68
+ expect(claims).toEqual({
69
+ sub: 'user-1',
70
+ clientId: 'abys_app_client',
71
+ scopes: [oauth_scope_catalogue_1.OAuthScopeName.CLOUD_FILE_READ, oauth_scope_catalogue_1.OAuthScopeName.PROFILE],
72
+ perimeter: { cloud: [{ unit: oauth_scope_enum_1.OAuthPerimeterUnit.SPACE, id: SPACE_ID }] },
73
+ audiences: [oauth_app_enum_1.OAuthAudience.ABYSS_CLOUD, oauth_app_enum_1.OAuthAudience.ABYSS_MAIN],
74
+ jti: 'jti-1',
75
+ expiresAt: new Date(exp * 1000),
76
+ });
77
+ });
78
+ it('accepts aud given as a single string', () => {
79
+ expect(verifyFor(appToken({ aud: oauth_app_enum_1.OAuthAudience.ABYSS_CLOUD })).audiences).toEqual([
80
+ oauth_app_enum_1.OAuthAudience.ABYSS_CLOUD,
81
+ ]);
82
+ });
83
+ it('refuses HS256 signed with the public key as the HMAC secret', () => {
84
+ const input = encode({ alg: 'HS256', typ: 'at+jwt' }, appPayload());
85
+ const signature = (0, crypto_1.createHmac)('sha256', publicKey).update(input).digest();
86
+ expect(reasonOf(`${input}.${base64url(signature)}`)).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
87
+ });
88
+ it('refuses alg none', () => {
89
+ const token = `${encode({ alg: 'none', typ: 'at+jwt' }, appPayload())}.`;
90
+ expect(reasonOf(token)).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
91
+ });
92
+ it('refuses a token signed by another key', () => {
93
+ expect(reasonOf(signRs256(AT_JWT, appPayload(), other.privateKey))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
94
+ });
95
+ it('refuses a token without typ', () => {
96
+ expect(reasonOf(signRs256({}, appPayload()))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
97
+ });
98
+ it('refuses typ JWT', () => {
99
+ expect(reasonOf(signRs256({ typ: 'JWT' }, appPayload()))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
100
+ });
101
+ it('refuses a token without aud', () => {
102
+ expect(reasonOf(appToken({ aud: undefined }))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.WRONG_AUDIENCE);
103
+ });
104
+ it('refuses a token whose aud does not hold the audience of the API', () => {
105
+ expect(reasonOf(appToken(), oauth_app_enum_1.OAuthAudience.ABYSS_WORKSPACE)).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.WRONG_AUDIENCE);
106
+ });
107
+ it('refuses an expired token', () => {
108
+ expect(reasonOf(appToken({ iat: nowSeconds() - 1000, exp: nowSeconds() - 10 }))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.EXPIRED);
109
+ });
110
+ it('refuses a session JWT (UUID, sid, typ JWT)', () => {
111
+ expect(reasonOf(sessionToken())).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
112
+ });
113
+ it.each(['UUID', 'sid'])('refuses an at+jwt that carries %s', (claim) => {
114
+ expect(reasonOf(appToken({ [claim]: 'value' }))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
115
+ });
116
+ it.each(['client_id', 'sub', 'jti', 'exp', 'abyss_scp', 'abyss_perimeter'])('refuses a payload without %s', (claim) => {
117
+ expect(reasonOf(appToken({ [claim]: undefined }))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
118
+ });
119
+ it('reads no scope from a plain scope claim: the bit field is the only source (CF44)', () => {
120
+ const claims = verifyFor(appToken({ scope: 'cloud:file.write', abyss_scp: (0, oauth_scope_bits_util_1.encodeOAuthScopes)([]) }));
121
+ expect(claims.scopes).toEqual([]);
122
+ });
123
+ it.each([
124
+ ['a malformed abyss_scp', { abyss_scp: { v: 1, s: { cloud: 'AA==' } } }],
125
+ [
126
+ 'an abyss_scp longer than the published positions',
127
+ { abyss_scp: { v: 1, s: { cloud: 'AAAAAA' } } },
128
+ ],
129
+ ['a malformed abyss_perimeter', { abyss_perimeter: { cloud: ['s:abc'] } }],
130
+ [
131
+ 'an abyss_perimeter that is not an object',
132
+ { abyss_perimeter: [`s:${(0, oauth_perimeter_claim_util_1.compactUuid)(SPACE_ID)}`] },
133
+ ],
134
+ ])('refuses %s as invalid_token', (_label, overrides) => {
135
+ expect(reasonOf(appToken(overrides))).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
136
+ });
137
+ it('refuses an unreadable token', () => {
138
+ expect(reasonOf('not-a-jwt')).toBe(oauth_access_token_util_1.OAuthAccessTokenErrorReason.INVALID_TOKEN);
139
+ });
140
+ });
141
+ describe('isOAuthAccessToken (CA20)', () => {
142
+ it('is true for an at+jwt, even before any verification', () => {
143
+ expect((0, oauth_access_token_util_1.isOAuthAccessToken)(appToken())).toBe(true);
144
+ expect((0, oauth_access_token_util_1.isOAuthAccessToken)(signRs256(AT_JWT, appPayload(), other.privateKey))).toBe(true);
145
+ });
146
+ it('is false for a session JWT', () => {
147
+ expect((0, oauth_access_token_util_1.isOAuthAccessToken)(sessionToken())).toBe(false);
148
+ });
149
+ it.each(['', 'garbage', 'a.b.c', `${base64url('{')}.${base64url('{}')}.x`])('is false for the unreadable token %p', (token) => {
150
+ expect((0, oauth_access_token_util_1.isOAuthAccessToken)(token)).toBe(false);
151
+ });
152
+ });
153
+ describe('session path (CA20)', () => {
154
+ it('assertSessionTokenNotOAuth refuses an at+jwt and lets a session through', () => {
155
+ expect(() => (0, oauth_access_token_util_1.assertSessionTokenNotOAuth)(appToken())).toThrow(oauth_access_token_util_1.OAuthAccessTokenError);
156
+ expect(() => (0, oauth_access_token_util_1.assertSessionTokenNotOAuth)(sessionToken())).not.toThrow();
157
+ });
158
+ it('SESSION_JWT_ALGORITHMS refuses a session forged in HS256 with the public key', () => {
159
+ const input = encode({ alg: 'HS256', typ: 'JWT' }, { UUID: 'user-1', sid: 's' });
160
+ const forged = `${input}.${base64url((0, crypto_1.createHmac)('sha256', publicKey).update(input).digest())}`;
161
+ expect(() => jsonwebtoken_1.default.verify(forged, publicKey, { algorithms: [...oauth_access_token_util_1.SESSION_JWT_ALGORITHMS] })).toThrow(jsonwebtoken_1.default.JsonWebTokenError);
162
+ expect(jsonwebtoken_1.default.verify(sessionToken(), publicKey, { algorithms: [...oauth_access_token_util_1.SESSION_JWT_ALGORITHMS] })).toMatchObject({ UUID: 'user-1', sid: 'session-1' });
163
+ });
164
+ });
165
+ });
166
+ //# sourceMappingURL=oauth-access-token.util.spec.js.map