@kya-os/mcp-i-runtime 1.0.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.
- package/.turbo/turbo-build.log +4 -0
- package/dist/auth/handshake.d.ts +136 -0
- package/dist/auth/handshake.d.ts.map +1 -0
- package/dist/auth/handshake.js +276 -0
- package/dist/auth/handshake.js.map +1 -0
- package/dist/auth/index.d.ts +6 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +12 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/types.d.ts +52 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth/types.js +10 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/cache/oauth-config-cache.d.ts +69 -0
- package/dist/cache/oauth-config-cache.d.ts.map +1 -0
- package/dist/cache/oauth-config-cache.js +76 -0
- package/dist/cache/oauth-config-cache.js.map +1 -0
- package/dist/cache/tool-protection-cache.d.ts +102 -0
- package/dist/cache/tool-protection-cache.d.ts.map +1 -0
- package/dist/cache/tool-protection-cache.js +131 -0
- package/dist/cache/tool-protection-cache.js.map +1 -0
- package/dist/compliance/index.d.ts +8 -0
- package/dist/compliance/index.d.ts.map +1 -0
- package/dist/compliance/index.js +24 -0
- package/dist/compliance/index.js.map +1 -0
- package/dist/compliance/schema-registry.d.ts +50 -0
- package/dist/compliance/schema-registry.d.ts.map +1 -0
- package/dist/compliance/schema-registry.js +438 -0
- package/dist/compliance/schema-registry.js.map +1 -0
- package/dist/compliance/schema-verifier.d.ts +110 -0
- package/dist/compliance/schema-verifier.d.ts.map +1 -0
- package/dist/compliance/schema-verifier.js +518 -0
- package/dist/compliance/schema-verifier.js.map +1 -0
- package/dist/config/remote-config.d.ts +188 -0
- package/dist/config/remote-config.d.ts.map +1 -0
- package/dist/config/remote-config.js +268 -0
- package/dist/config/remote-config.js.map +1 -0
- package/dist/config.d.ts +182 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +148 -0
- package/dist/config.js.map +1 -0
- package/dist/identity/idp-token-resolver.d.ts +69 -0
- package/dist/identity/idp-token-resolver.d.ts.map +1 -0
- package/dist/identity/idp-token-resolver.js +136 -0
- package/dist/identity/idp-token-resolver.js.map +1 -0
- package/dist/identity/idp-token-storage.interface.d.ts +80 -0
- package/dist/identity/idp-token-storage.interface.d.ts.map +1 -0
- package/dist/identity/idp-token-storage.interface.js +14 -0
- package/dist/identity/idp-token-storage.interface.js.map +1 -0
- package/dist/identity/user-did-manager.d.ts +228 -0
- package/dist/identity/user-did-manager.d.ts.map +1 -0
- package/dist/identity/user-did-manager.js +356 -0
- package/dist/identity/user-did-manager.js.map +1 -0
- package/dist/index.d.ts +69 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +193 -0
- package/dist/index.js.map +1 -0
- package/dist/logging/index.d.ts +5 -0
- package/dist/logging/index.d.ts.map +1 -0
- package/dist/logging/index.js +10 -0
- package/dist/logging/index.js.map +1 -0
- package/dist/logging/logger.d.ts +33 -0
- package/dist/logging/logger.d.ts.map +1 -0
- package/dist/logging/logger.js +104 -0
- package/dist/logging/logger.js.map +1 -0
- package/dist/proof/generator.d.ts +109 -0
- package/dist/proof/generator.d.ts.map +1 -0
- package/dist/proof/generator.js +236 -0
- package/dist/proof/generator.js.map +1 -0
- package/dist/proof/index.d.ts +5 -0
- package/dist/proof/index.d.ts.map +1 -0
- package/dist/proof/index.js +11 -0
- package/dist/proof/index.js.map +1 -0
- package/dist/providers/base.d.ts +95 -0
- package/dist/providers/base.d.ts.map +1 -0
- package/dist/providers/base.js +47 -0
- package/dist/providers/base.js.map +1 -0
- package/dist/providers/memory.d.ts +42 -0
- package/dist/providers/memory.d.ts.map +1 -0
- package/dist/providers/memory.js +121 -0
- package/dist/providers/memory.js.map +1 -0
- package/dist/runtime/audit-logger.d.ts +37 -0
- package/dist/runtime/audit-logger.d.ts.map +1 -0
- package/dist/runtime/audit-logger.js +9 -0
- package/dist/runtime/audit-logger.js.map +1 -0
- package/dist/runtime/base.d.ts +392 -0
- package/dist/runtime/base.d.ts.map +1 -0
- package/dist/runtime/base.js +1527 -0
- package/dist/runtime/base.js.map +1 -0
- package/dist/runtime/dif-core.d.ts +33 -0
- package/dist/runtime/dif-core.d.ts.map +1 -0
- package/dist/runtime/dif-core.js +14 -0
- package/dist/runtime/dif-core.js.map +1 -0
- package/dist/runtime/ext-apps-constants.d.ts +20 -0
- package/dist/runtime/ext-apps-constants.d.ts.map +1 -0
- package/dist/runtime/ext-apps-constants.js +23 -0
- package/dist/runtime/ext-apps-constants.js.map +1 -0
- package/dist/services/access-control.service.d.ts +138 -0
- package/dist/services/access-control.service.d.ts.map +1 -0
- package/dist/services/access-control.service.js +721 -0
- package/dist/services/access-control.service.js.map +1 -0
- package/dist/services/authorization/authorization-registry.d.ts +29 -0
- package/dist/services/authorization/authorization-registry.d.ts.map +1 -0
- package/dist/services/authorization/authorization-registry.js +58 -0
- package/dist/services/authorization/authorization-registry.js.map +1 -0
- package/dist/services/authorization/types.d.ts +53 -0
- package/dist/services/authorization/types.d.ts.map +1 -0
- package/dist/services/authorization/types.js +10 -0
- package/dist/services/authorization/types.js.map +1 -0
- package/dist/services/batch-delegation.service.d.ts +53 -0
- package/dist/services/batch-delegation.service.d.ts.map +1 -0
- package/dist/services/batch-delegation.service.js +95 -0
- package/dist/services/batch-delegation.service.js.map +1 -0
- package/dist/services/crypto.service.d.ts +69 -0
- package/dist/services/crypto.service.d.ts.map +1 -0
- package/dist/services/crypto.service.js +225 -0
- package/dist/services/crypto.service.js.map +1 -0
- package/dist/services/delegation-error-formatter.d.ts +124 -0
- package/dist/services/delegation-error-formatter.d.ts.map +1 -0
- package/dist/services/delegation-error-formatter.js +214 -0
- package/dist/services/delegation-error-formatter.js.map +1 -0
- package/dist/services/errors.d.ts +49 -0
- package/dist/services/errors.d.ts.map +1 -0
- package/dist/services/errors.js +66 -0
- package/dist/services/errors.js.map +1 -0
- package/dist/services/index.d.ts +9 -0
- package/dist/services/index.d.ts.map +1 -0
- package/dist/services/index.js +15 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/oauth-config.service.d.ts +53 -0
- package/dist/services/oauth-config.service.d.ts.map +1 -0
- package/dist/services/oauth-config.service.js +141 -0
- package/dist/services/oauth-config.service.js.map +1 -0
- package/dist/services/oauth-provider-registry.d.ts +88 -0
- package/dist/services/oauth-provider-registry.d.ts.map +1 -0
- package/dist/services/oauth-provider-registry.js +128 -0
- package/dist/services/oauth-provider-registry.js.map +1 -0
- package/dist/services/oauth-service.d.ts +122 -0
- package/dist/services/oauth-service.d.ts.map +1 -0
- package/dist/services/oauth-service.js +442 -0
- package/dist/services/oauth-service.js.map +1 -0
- package/dist/services/oauth-token-retrieval.service.d.ts +49 -0
- package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -0
- package/dist/services/oauth-token-retrieval.service.js +150 -0
- package/dist/services/oauth-token-retrieval.service.js.map +1 -0
- package/dist/services/policy.service.d.ts +130 -0
- package/dist/services/policy.service.d.ts.map +1 -0
- package/dist/services/policy.service.js +399 -0
- package/dist/services/policy.service.js.map +1 -0
- package/dist/services/proof-verifier.d.ts +103 -0
- package/dist/services/proof-verifier.d.ts.map +1 -0
- package/dist/services/proof-verifier.js +190 -0
- package/dist/services/proof-verifier.js.map +1 -0
- package/dist/services/provider-resolver.d.ts +89 -0
- package/dist/services/provider-resolver.d.ts.map +1 -0
- package/dist/services/provider-resolver.js +196 -0
- package/dist/services/provider-resolver.js.map +1 -0
- package/dist/services/provider-validator.d.ts +55 -0
- package/dist/services/provider-validator.d.ts.map +1 -0
- package/dist/services/provider-validator.js +135 -0
- package/dist/services/provider-validator.js.map +1 -0
- package/dist/services/session-registration.service.d.ts +80 -0
- package/dist/services/session-registration.service.d.ts.map +1 -0
- package/dist/services/session-registration.service.js +174 -0
- package/dist/services/session-registration.service.js.map +1 -0
- package/dist/services/storage.service.d.ts +116 -0
- package/dist/services/storage.service.d.ts.map +1 -0
- package/dist/services/storage.service.js +411 -0
- package/dist/services/storage.service.js.map +1 -0
- package/dist/services/tool-context-builder.d.ts +74 -0
- package/dist/services/tool-context-builder.d.ts.map +1 -0
- package/dist/services/tool-context-builder.js +215 -0
- package/dist/services/tool-context-builder.js.map +1 -0
- package/dist/services/tool-protection.service.d.ts +209 -0
- package/dist/services/tool-protection.service.d.ts.map +1 -0
- package/dist/services/tool-protection.service.js +752 -0
- package/dist/services/tool-protection.service.js.map +1 -0
- package/dist/session/index.d.ts +5 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/index.js +11 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/manager.d.ts +118 -0
- package/dist/session/manager.d.ts.map +1 -0
- package/dist/session/manager.js +285 -0
- package/dist/session/manager.js.map +1 -0
- package/dist/types/oauth-required-error.d.ts +46 -0
- package/dist/types/oauth-required-error.d.ts.map +1 -0
- package/dist/types/oauth-required-error.js +42 -0
- package/dist/types/oauth-required-error.js.map +1 -0
- package/dist/types/tool-protection.d.ts +144 -0
- package/dist/types/tool-protection.d.ts.map +1 -0
- package/dist/types/tool-protection.js +48 -0
- package/dist/types/tool-protection.js.map +1 -0
- package/dist/utils/base58.d.ts +31 -0
- package/dist/utils/base58.d.ts.map +1 -0
- package/dist/utils/base58.js +103 -0
- package/dist/utils/base58.js.map +1 -0
- package/dist/utils/base64.d.ts +32 -0
- package/dist/utils/base64.d.ts.map +1 -0
- package/dist/utils/base64.js +172 -0
- package/dist/utils/base64.js.map +1 -0
- package/dist/utils/cors.d.ts +52 -0
- package/dist/utils/cors.d.ts.map +1 -0
- package/dist/utils/cors.js +79 -0
- package/dist/utils/cors.js.map +1 -0
- package/dist/utils/did-helpers.d.ts +168 -0
- package/dist/utils/did-helpers.d.ts.map +1 -0
- package/dist/utils/did-helpers.js +222 -0
- package/dist/utils/did-helpers.js.map +1 -0
- package/dist/utils/index.d.ts +8 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +24 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/storage-keys.d.ts +120 -0
- package/dist/utils/storage-keys.d.ts.map +1 -0
- package/dist/utils/storage-keys.js +217 -0
- package/dist/utils/storage-keys.js.map +1 -0
- package/dist/wire-format.d.ts +62 -0
- package/dist/wire-format.d.ts.map +1 -0
- package/dist/wire-format.js +89 -0
- package/dist/wire-format.js.map +1 -0
- package/package.json +83 -0
- package/src/__tests__/cache/tool-protection-cache.test.ts +640 -0
- package/src/__tests__/config/provider-runtime-config.test.ts +309 -0
- package/src/__tests__/config.test.ts +307 -0
- package/src/__tests__/identity/user-did-manager.test.ts +232 -0
- package/src/__tests__/index.test.ts +56 -0
- package/src/__tests__/integration/full-flow.test.ts +779 -0
- package/src/__tests__/integration.test.ts +281 -0
- package/src/__tests__/providers/base.test.ts +173 -0
- package/src/__tests__/providers/memory.test.ts +319 -0
- package/src/__tests__/regression/phase2-regression.test.ts +406 -0
- package/src/__tests__/runtime/audit-logger.test.ts +154 -0
- package/src/__tests__/runtime/base-extensions.test.ts +595 -0
- package/src/__tests__/runtime/base.test.ts +1328 -0
- package/src/__tests__/runtime/delegation-flow.test.ts +159 -0
- package/src/__tests__/runtime/process-tool-call-security.test.ts +1024 -0
- package/src/__tests__/runtime/proof-client-did.test.ts +376 -0
- package/src/__tests__/runtime/provider-selection.test.ts +292 -0
- package/src/__tests__/runtime/route-interception.test.ts +670 -0
- package/src/__tests__/runtime/tool-protection-enforcement.test.ts +989 -0
- package/src/__tests__/services/access-control-retry.test.ts +595 -0
- package/src/__tests__/services/agentshield-integration.test.ts +709 -0
- package/src/__tests__/services/cache-busting.test.ts +125 -0
- package/src/__tests__/services/oauth-service-errors.test.ts +704 -0
- package/src/__tests__/services/oauth-service-pkce.test.ts +556 -0
- package/src/__tests__/services/oauth-service-secret-resolution.test.ts +349 -0
- package/src/__tests__/services/provider-resolver-edge-cases.test.ts +591 -0
- package/src/__tests__/services/tool-protection-failsafe.test.ts +683 -0
- package/src/__tests__/services/tool-protection-merged-config.test.ts +664 -0
- package/src/__tests__/services/tool-protection-oauth-provider.test.ts +300 -0
- package/src/__tests__/services/tool-protection.service.test.ts +1201 -0
- package/src/__tests__/utils/mock-providers.ts +340 -0
- package/src/__tests__/wire-format.test.ts +123 -0
- package/src/auth/__tests__/resume-token.test.ts +42 -0
- package/src/auth/handshake.ts +476 -0
- package/src/auth/index.ts +15 -0
- package/src/auth/types.ts +68 -0
- package/src/cache/__tests__/oauth-config-cache.test.ts +215 -0
- package/src/cache/oauth-config-cache.d.ts +69 -0
- package/src/cache/oauth-config-cache.d.ts.map +1 -0
- package/src/cache/oauth-config-cache.js.map +1 -0
- package/src/cache/oauth-config-cache.ts +123 -0
- package/src/cache/tool-protection-cache.ts +184 -0
- package/src/compliance/EXAMPLE.md +412 -0
- package/src/compliance/__tests__/schema-verifier.test.ts +791 -0
- package/src/compliance/index.ts +8 -0
- package/src/compliance/schema-registry.ts +460 -0
- package/src/compliance/schema-verifier.ts +708 -0
- package/src/config/__tests__/merged-config.spec.ts +445 -0
- package/src/config/__tests__/remote-config-edge-cases.test.ts +424 -0
- package/src/config/__tests__/remote-config-helpers.test.ts +280 -0
- package/src/config/__tests__/remote-config.spec.ts +265 -0
- package/src/config/remote-config.ts +368 -0
- package/src/config.ts +312 -0
- package/src/identity/__tests__/idp-token-resolver.test.ts +340 -0
- package/src/identity/__tests__/user-did-manager.test.ts +487 -0
- package/src/identity/idp-token-resolver.ts +181 -0
- package/src/identity/idp-token-storage.interface.ts +102 -0
- package/src/identity/user-did-manager.ts +592 -0
- package/src/index.ts +331 -0
- package/src/logging/__tests__/logger.test.ts +366 -0
- package/src/logging/index.ts +10 -0
- package/src/logging/logger.ts +112 -0
- package/src/proof/__tests__/crypto-parity.test.ts +202 -0
- package/src/proof/__tests__/proof-generator.test.ts +484 -0
- package/src/proof/generator.ts +347 -0
- package/src/proof/index.ts +12 -0
- package/src/providers/base.d.ts +91 -0
- package/src/providers/base.d.ts.map +1 -0
- package/src/providers/base.js.map +1 -0
- package/src/providers/base.ts +100 -0
- package/src/providers/memory.ts +142 -0
- package/src/runtime/__tests__/dif-esm-bridge.test.ts +33 -0
- package/src/runtime/__tests__/ext-apps-consent.test.ts +334 -0
- package/src/runtime/audit-logger.ts +39 -0
- package/src/runtime/base.ts +2100 -0
- package/src/runtime/dif-core.ts +39 -0
- package/src/runtime/ext-apps-constants.ts +20 -0
- package/src/services/__tests__/access-control.integration.test.ts +441 -0
- package/src/services/__tests__/access-control.proof-response-validation.test.ts +578 -0
- package/src/services/__tests__/access-control.service.test.ts +1132 -0
- package/src/services/__tests__/batch-delegation.service.test.ts +351 -0
- package/src/services/__tests__/crypto.service.test.ts +531 -0
- package/src/services/__tests__/delegation-error-formatter.test.ts +643 -0
- package/src/services/__tests__/oauth-config.service.test.ts +359 -0
- package/src/services/__tests__/oauth-provider-registry.test.ts +142 -0
- package/src/services/__tests__/oauth-token-retrieval.service.test.ts +365 -0
- package/src/services/__tests__/proof-verifier.integration.test.ts +494 -0
- package/src/services/__tests__/proof-verifier.test.ts +489 -0
- package/src/services/__tests__/provider-resolution.integration.test.ts +202 -0
- package/src/services/__tests__/provider-resolver.test.ts +213 -0
- package/src/services/__tests__/provider-validator.test.ts +370 -0
- package/src/services/__tests__/session-registration.service.test.ts +312 -0
- package/src/services/__tests__/storage.service.test.ts +358 -0
- package/src/services/__tests__/tool-context-builder.test.ts +438 -0
- package/src/services/access-control.service.ts +1048 -0
- package/src/services/authorization/authorization-registry.ts +67 -0
- package/src/services/authorization/types.ts +71 -0
- package/src/services/batch-delegation.service.ts +136 -0
- package/src/services/crypto.service.ts +296 -0
- package/src/services/delegation-error-formatter.ts +299 -0
- package/src/services/errors.ts +76 -0
- package/src/services/index.ts +34 -0
- package/src/services/oauth-config.service.d.ts +53 -0
- package/src/services/oauth-config.service.d.ts.map +1 -0
- package/src/services/oauth-config.service.js.map +1 -0
- package/src/services/oauth-config.service.ts +192 -0
- package/src/services/oauth-provider-registry.d.ts +57 -0
- package/src/services/oauth-provider-registry.d.ts.map +1 -0
- package/src/services/oauth-provider-registry.js.map +1 -0
- package/src/services/oauth-provider-registry.ts +141 -0
- package/src/services/oauth-service.ts +652 -0
- package/src/services/oauth-token-retrieval.service.ts +245 -0
- package/src/services/policy.service.ts +527 -0
- package/src/services/proof-verifier.ts +295 -0
- package/src/services/provider-resolver.d.ts +48 -0
- package/src/services/provider-resolver.d.ts.map +1 -0
- package/src/services/provider-resolver.js.map +1 -0
- package/src/services/provider-resolver.ts +236 -0
- package/src/services/provider-validator.ts +170 -0
- package/src/services/session-registration.service.ts +259 -0
- package/src/services/storage.service.ts +566 -0
- package/src/services/tool-context-builder.ts +285 -0
- package/src/services/tool-protection.service.ts +971 -0
- package/src/session/__tests__/session-manager.test.ts +327 -0
- package/src/session/index.ts +10 -0
- package/src/session/manager.ts +380 -0
- package/src/types/__tests__/oauth-required-error.test.ts +79 -0
- package/src/types/__tests__/tool-protection.test.ts +121 -0
- package/src/types/oauth-required-error.ts +71 -0
- package/src/types/tool-protection.ts +179 -0
- package/src/utils/__tests__/base58.test.ts +281 -0
- package/src/utils/__tests__/base64.test.ts +239 -0
- package/src/utils/__tests__/cors.test.ts +184 -0
- package/src/utils/__tests__/did-helpers.test.ts +156 -0
- package/src/utils/__tests__/storage-keys.test.ts +372 -0
- package/src/utils/base58.ts +109 -0
- package/src/utils/base64.ts +185 -0
- package/src/utils/cors.ts +93 -0
- package/src/utils/did-helpers.ts +229 -0
- package/src/utils/index.ts +8 -0
- package/src/utils/storage-keys.ts +285 -0
- package/src/wire-format.ts +114 -0
- package/tsconfig.json +21 -0
- package/vitest.config.mts +57 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for Storage Key Utilities
|
|
3
|
+
*
|
|
4
|
+
* Covers:
|
|
5
|
+
* - Key generation functions
|
|
6
|
+
* - Migration utilities
|
|
7
|
+
* - Storage key constants
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
11
|
+
import { legacyDelegationKey, compositeDelegationKey, sessionKey, userDidKey, oauthIdentityKey, verificationCacheKey, nonceKey, migrateDelegationKeys, STORAGE_KEYS, type StorageProvider } from "../storage-keys";
|
|
12
|
+
|
|
13
|
+
describe("Storage Key Utilities", () => {
|
|
14
|
+
describe("Key Generation Functions", () => {
|
|
15
|
+
describe("legacyDelegationKey", () => {
|
|
16
|
+
it("should generate correct legacy key format", () => {
|
|
17
|
+
const agentDid = "did:key:z6MkAgent123";
|
|
18
|
+
const key = legacyDelegationKey(agentDid);
|
|
19
|
+
expect(key).toBe("agent:did:key:z6MkAgent123:delegation");
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("should handle DIDs with various formats", () => {
|
|
23
|
+
const didWeb = "did:web:example.com:agent";
|
|
24
|
+
expect(legacyDelegationKey(didWeb)).toBe(
|
|
25
|
+
"agent:did:web:example.com:agent:delegation"
|
|
26
|
+
);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe("compositeDelegationKey", () => {
|
|
31
|
+
it("should generate correct composite key without projectId", () => {
|
|
32
|
+
const userDid = "did:key:z6MkUser123";
|
|
33
|
+
const agentDid = "did:key:z6MkAgent456";
|
|
34
|
+
const key = compositeDelegationKey(userDid, agentDid);
|
|
35
|
+
expect(key).toBe(
|
|
36
|
+
"delegation:user:did:key:z6MkUser123:agent:did:key:z6MkAgent456"
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("should generate correct composite key with projectId", () => {
|
|
41
|
+
const userDid = "did:key:z6MkUser123";
|
|
42
|
+
const agentDid = "did:key:z6MkAgent456";
|
|
43
|
+
const projectId = "proj-789";
|
|
44
|
+
const key = compositeDelegationKey(userDid, agentDid, projectId);
|
|
45
|
+
expect(key).toBe(
|
|
46
|
+
"delegation:user:did:key:z6MkUser123:agent:did:key:z6MkAgent456:project:proj-789"
|
|
47
|
+
);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("should handle empty projectId as no projectId", () => {
|
|
51
|
+
const userDid = "did:key:z6MkUser123";
|
|
52
|
+
const agentDid = "did:key:z6MkAgent456";
|
|
53
|
+
const key = compositeDelegationKey(userDid, agentDid, "");
|
|
54
|
+
expect(key).toBe(
|
|
55
|
+
"delegation:user:did:key:z6MkUser123:agent:did:key:z6MkAgent456"
|
|
56
|
+
);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe("sessionKey", () => {
|
|
61
|
+
it("should generate correct session key format", () => {
|
|
62
|
+
const sessionId = "sess-abc123";
|
|
63
|
+
const key = sessionKey(sessionId);
|
|
64
|
+
expect(key).toBe("session:sess-abc123");
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("should handle UUID session IDs", () => {
|
|
68
|
+
const sessionId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
|
69
|
+
const key = sessionKey(sessionId);
|
|
70
|
+
expect(key).toBe(`session:${sessionId}`);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
describe("userDidKey", () => {
|
|
75
|
+
it("should generate correct user DID key format", () => {
|
|
76
|
+
const provider = "github";
|
|
77
|
+
const subject = "user123";
|
|
78
|
+
const key = userDidKey(provider, subject);
|
|
79
|
+
expect(key).toBe("userDid:oauth:github:user123");
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("should handle email subjects", () => {
|
|
83
|
+
const provider = "google";
|
|
84
|
+
const subject = "user@example.com";
|
|
85
|
+
const key = userDidKey(provider, subject);
|
|
86
|
+
expect(key).toBe("userDid:oauth:google:user@example.com");
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe("oauthIdentityKey", () => {
|
|
91
|
+
it("should generate correct OAuth identity key format", () => {
|
|
92
|
+
const provider = "github";
|
|
93
|
+
const subject = "12345678";
|
|
94
|
+
const key = oauthIdentityKey(provider, subject);
|
|
95
|
+
expect(key).toBe("oauth:github:12345678");
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
describe("verificationCacheKey", () => {
|
|
100
|
+
it("should generate correct verification cache key format", () => {
|
|
101
|
+
const tokenHash = "abc123def456";
|
|
102
|
+
const key = verificationCacheKey(tokenHash);
|
|
103
|
+
expect(key).toBe("verified:abc123def456");
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe("nonceKey", () => {
|
|
108
|
+
it("should generate correct nonce key format", () => {
|
|
109
|
+
const nonce = "unique-nonce-789";
|
|
110
|
+
const key = nonceKey(nonce);
|
|
111
|
+
expect(key).toBe("nonce:unique-nonce-789");
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe("STORAGE_KEYS constant", () => {
|
|
117
|
+
it("should expose all key functions", () => {
|
|
118
|
+
expect(STORAGE_KEYS.userDid).toBe(userDidKey);
|
|
119
|
+
expect(STORAGE_KEYS.oauthIdentity).toBe(oauthIdentityKey);
|
|
120
|
+
expect(STORAGE_KEYS.delegation).toBe(compositeDelegationKey);
|
|
121
|
+
expect(STORAGE_KEYS.session).toBe(sessionKey);
|
|
122
|
+
expect(STORAGE_KEYS.legacyDelegation).toBe(legacyDelegationKey);
|
|
123
|
+
expect(STORAGE_KEYS.verificationCache).toBe(verificationCacheKey);
|
|
124
|
+
expect(STORAGE_KEYS.nonce).toBe(nonceKey);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("should generate consistent keys when used as methods", () => {
|
|
128
|
+
expect(STORAGE_KEYS.session("test-session")).toBe("session:test-session");
|
|
129
|
+
expect(STORAGE_KEYS.nonce("test-nonce")).toBe("nonce:test-nonce");
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
describe("migrateDelegationKeys", () => {
|
|
134
|
+
let mockStorage: StorageProvider;
|
|
135
|
+
|
|
136
|
+
beforeEach(() => {
|
|
137
|
+
mockStorage = {
|
|
138
|
+
get: vi.fn(),
|
|
139
|
+
set: vi.fn(),
|
|
140
|
+
delete: vi.fn(),
|
|
141
|
+
exists: vi.fn(),
|
|
142
|
+
list: vi.fn(),
|
|
143
|
+
};
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("should return empty result when no legacy keys found", async () => {
|
|
147
|
+
vi.mocked(mockStorage.list).mockResolvedValue([]);
|
|
148
|
+
|
|
149
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
150
|
+
|
|
151
|
+
expect(result.migrated).toBe(0);
|
|
152
|
+
expect(result.failed).toBe(0);
|
|
153
|
+
expect(result.migrations).toHaveLength(0);
|
|
154
|
+
expect(result.errors).toHaveLength(0);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("should find and migrate legacy delegation keys", async () => {
|
|
158
|
+
// Use simple agent ID that matches the regex pattern [^:]+
|
|
159
|
+
const agentId = "agent123";
|
|
160
|
+
const userDid = "did:key:z6MkUser456";
|
|
161
|
+
const legacyKey = `agent:${agentId}:delegation`;
|
|
162
|
+
const delegationToken = "test-delegation-token";
|
|
163
|
+
|
|
164
|
+
// Setup mocks
|
|
165
|
+
vi.mocked(mockStorage.list)
|
|
166
|
+
.mockResolvedValueOnce([legacyKey]) // Legacy keys
|
|
167
|
+
.mockResolvedValueOnce(["session:sess-123"]); // Session keys
|
|
168
|
+
|
|
169
|
+
vi.mocked(mockStorage.get)
|
|
170
|
+
.mockResolvedValueOnce(delegationToken) // Legacy key value
|
|
171
|
+
.mockResolvedValueOnce(JSON.stringify({ userDid, agentDid: agentId })); // Session data
|
|
172
|
+
|
|
173
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
174
|
+
|
|
175
|
+
expect(result.migrated).toBe(1);
|
|
176
|
+
expect(result.failed).toBe(0);
|
|
177
|
+
expect(result.migrations[0].oldKey).toBe(legacyKey);
|
|
178
|
+
expect(result.migrations[0].newKey).toContain(userDid);
|
|
179
|
+
expect(mockStorage.set).toHaveBeenCalledWith(
|
|
180
|
+
expect.stringContaining("delegation:user:"),
|
|
181
|
+
delegationToken
|
|
182
|
+
);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("should skip keys with no value", async () => {
|
|
186
|
+
const legacyKey = "agent:simpleAgentId:delegation";
|
|
187
|
+
|
|
188
|
+
vi.mocked(mockStorage.list)
|
|
189
|
+
.mockResolvedValueOnce([legacyKey])
|
|
190
|
+
.mockResolvedValueOnce([]);
|
|
191
|
+
|
|
192
|
+
vi.mocked(mockStorage.get).mockResolvedValue(null);
|
|
193
|
+
|
|
194
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
195
|
+
|
|
196
|
+
expect(result.migrated).toBe(0);
|
|
197
|
+
expect(mockStorage.set).not.toHaveBeenCalled();
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("should handle dry-run mode", async () => {
|
|
201
|
+
const agentId = "agent123";
|
|
202
|
+
const userDid = "did:key:z6MkUser456";
|
|
203
|
+
const legacyKey = `agent:${agentId}:delegation`;
|
|
204
|
+
|
|
205
|
+
vi.mocked(mockStorage.list)
|
|
206
|
+
.mockResolvedValueOnce([legacyKey])
|
|
207
|
+
.mockResolvedValueOnce(["session:sess-123"]);
|
|
208
|
+
|
|
209
|
+
vi.mocked(mockStorage.get)
|
|
210
|
+
.mockResolvedValueOnce("token")
|
|
211
|
+
.mockResolvedValueOnce(JSON.stringify({ userDid, agentDid: agentId }));
|
|
212
|
+
|
|
213
|
+
const result = await migrateDelegationKeys(mockStorage, { dryRun: true });
|
|
214
|
+
|
|
215
|
+
expect(result.migrated).toBe(1);
|
|
216
|
+
expect(mockStorage.set).not.toHaveBeenCalled();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("should delete old keys when deleteOldKeys is true", async () => {
|
|
220
|
+
const agentId = "agent123";
|
|
221
|
+
const userDid = "did:key:z6MkUser456";
|
|
222
|
+
const legacyKey = `agent:${agentId}:delegation`;
|
|
223
|
+
|
|
224
|
+
vi.mocked(mockStorage.list)
|
|
225
|
+
.mockResolvedValueOnce([legacyKey])
|
|
226
|
+
.mockResolvedValueOnce(["session:sess-123"]);
|
|
227
|
+
|
|
228
|
+
vi.mocked(mockStorage.get)
|
|
229
|
+
.mockResolvedValueOnce("token")
|
|
230
|
+
.mockResolvedValueOnce(JSON.stringify({ userDid, agentDid: agentId }));
|
|
231
|
+
|
|
232
|
+
const result = await migrateDelegationKeys(mockStorage, {
|
|
233
|
+
deleteOldKeys: true,
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
expect(result.migrated).toBe(1);
|
|
237
|
+
expect(mockStorage.delete).toHaveBeenCalledWith(legacyKey);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("should use custom userDid resolver when provided", async () => {
|
|
241
|
+
const agentId = "agent123";
|
|
242
|
+
const userDid = "did:key:z6MkResolvedUser";
|
|
243
|
+
const legacyKey = `agent:${agentId}:delegation`;
|
|
244
|
+
|
|
245
|
+
vi.mocked(mockStorage.list)
|
|
246
|
+
.mockResolvedValueOnce([legacyKey])
|
|
247
|
+
.mockResolvedValueOnce([]);
|
|
248
|
+
|
|
249
|
+
vi.mocked(mockStorage.get).mockResolvedValueOnce("token");
|
|
250
|
+
|
|
251
|
+
const mockResolver = vi.fn().mockResolvedValue(userDid);
|
|
252
|
+
|
|
253
|
+
const result = await migrateDelegationKeys(mockStorage, {
|
|
254
|
+
resolveUserDid: mockResolver,
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
expect(result.migrated).toBe(1);
|
|
258
|
+
expect(mockResolver).toHaveBeenCalledWith(agentId, undefined);
|
|
259
|
+
expect(result.migrations[0].newKey).toContain(userDid);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("should filter out keys that don't match legacy format", async () => {
|
|
263
|
+
// Keys with colons in the middle don't match the regex ^agent:[^:]+:delegation$
|
|
264
|
+
vi.mocked(mockStorage.list).mockResolvedValueOnce([
|
|
265
|
+
"agent:invalid:format:delegation", // Has extra colons
|
|
266
|
+
"agent:valid:delegation", // This matches
|
|
267
|
+
"agent:missing-suffix", // Missing :delegation
|
|
268
|
+
]);
|
|
269
|
+
|
|
270
|
+
vi.mocked(mockStorage.get).mockResolvedValue(null);
|
|
271
|
+
|
|
272
|
+
await migrateDelegationKeys(mockStorage);
|
|
273
|
+
|
|
274
|
+
// Only "agent:valid:delegation" matches the regex
|
|
275
|
+
expect(mockStorage.get).toHaveBeenCalledTimes(1);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("should record error when userDid cannot be resolved", async () => {
|
|
279
|
+
const legacyKey = "agent:simpleAgent:delegation";
|
|
280
|
+
|
|
281
|
+
vi.mocked(mockStorage.list)
|
|
282
|
+
.mockResolvedValueOnce([legacyKey])
|
|
283
|
+
.mockResolvedValueOnce([]); // No sessions
|
|
284
|
+
|
|
285
|
+
vi.mocked(mockStorage.get).mockResolvedValueOnce("token");
|
|
286
|
+
|
|
287
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
288
|
+
|
|
289
|
+
expect(result.failed).toBe(1);
|
|
290
|
+
expect(result.errors[0].error).toContain("Cannot resolve userDid");
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it("should handle storage errors gracefully", async () => {
|
|
294
|
+
vi.mocked(mockStorage.list).mockRejectedValueOnce(
|
|
295
|
+
new Error("Storage error")
|
|
296
|
+
);
|
|
297
|
+
|
|
298
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
299
|
+
|
|
300
|
+
expect(result.errors.length).toBeGreaterThan(0);
|
|
301
|
+
expect(result.errors[0].error).toContain("Storage error");
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it("should continue processing after individual key errors", async () => {
|
|
305
|
+
const legacyKey1 = "agent:agent1:delegation";
|
|
306
|
+
const legacyKey2 = "agent:agent2:delegation";
|
|
307
|
+
const userDid = "did:key:z6MkUser";
|
|
308
|
+
|
|
309
|
+
vi.mocked(mockStorage.list)
|
|
310
|
+
.mockResolvedValueOnce([legacyKey1, legacyKey2])
|
|
311
|
+
.mockResolvedValueOnce([]) // First key: no sessions
|
|
312
|
+
.mockResolvedValueOnce(["session:s1"]); // Second key: has session
|
|
313
|
+
|
|
314
|
+
vi.mocked(mockStorage.get)
|
|
315
|
+
.mockResolvedValueOnce("token1")
|
|
316
|
+
.mockResolvedValueOnce("token2")
|
|
317
|
+
.mockResolvedValueOnce(JSON.stringify({ userDid, agentDid: "agent2" }));
|
|
318
|
+
|
|
319
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
320
|
+
|
|
321
|
+
expect(result.failed).toBe(1);
|
|
322
|
+
expect(result.migrated).toBe(1);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it("should extract sessionId from session key correctly", async () => {
|
|
326
|
+
const agentId = "agent123";
|
|
327
|
+
const userDid = "did:key:z6MkUser456";
|
|
328
|
+
const legacyKey = `agent:${agentId}:delegation`;
|
|
329
|
+
const sessionId = "session-uuid-123";
|
|
330
|
+
|
|
331
|
+
vi.mocked(mockStorage.list)
|
|
332
|
+
.mockResolvedValueOnce([legacyKey])
|
|
333
|
+
.mockResolvedValueOnce([`session:${sessionId}`]);
|
|
334
|
+
|
|
335
|
+
vi.mocked(mockStorage.get)
|
|
336
|
+
.mockResolvedValueOnce("token")
|
|
337
|
+
.mockResolvedValueOnce(JSON.stringify({ userDid, agentDid: agentId }));
|
|
338
|
+
|
|
339
|
+
const mockResolver = vi.fn().mockResolvedValue(null);
|
|
340
|
+
|
|
341
|
+
await migrateDelegationKeys(mockStorage, {
|
|
342
|
+
resolveUserDid: mockResolver,
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
// Resolver should be called with sessionId context
|
|
346
|
+
expect(mockResolver).toHaveBeenCalledWith(agentId, sessionId);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it("should handle non-JSON session data gracefully", async () => {
|
|
350
|
+
const legacyKey = "agent:simpleAgent:delegation";
|
|
351
|
+
|
|
352
|
+
vi.mocked(mockStorage.list)
|
|
353
|
+
.mockResolvedValueOnce([legacyKey])
|
|
354
|
+
.mockResolvedValueOnce(["session:s1"]);
|
|
355
|
+
|
|
356
|
+
vi.mocked(mockStorage.get)
|
|
357
|
+
.mockResolvedValueOnce("token")
|
|
358
|
+
.mockResolvedValueOnce("not-json-data");
|
|
359
|
+
|
|
360
|
+
const result = await migrateDelegationKeys(mockStorage);
|
|
361
|
+
|
|
362
|
+
// Should fail because userDid cannot be extracted from non-JSON session data
|
|
363
|
+
expect(result.failed).toBe(1);
|
|
364
|
+
});
|
|
365
|
+
});
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base58 Utilities (Bitcoin alphabet)
|
|
3
|
+
*
|
|
4
|
+
* Encoding and decoding utilities for Base58 (Bitcoin alphabet).
|
|
5
|
+
* Used for did:key multibase encoding (with 'z' prefix for base58btc).
|
|
6
|
+
*
|
|
7
|
+
* The Bitcoin alphabet excludes ambiguous characters (0, O, I, l).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
11
|
+
const ALPHABET_MAP = new Map<string, number>();
|
|
12
|
+
|
|
13
|
+
// Build reverse lookup map
|
|
14
|
+
for (let i = 0; i < ALPHABET.length; i++) {
|
|
15
|
+
ALPHABET_MAP.set(ALPHABET[i], i);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Encode bytes to Base58 (Bitcoin alphabet)
|
|
20
|
+
*
|
|
21
|
+
* @param bytes - Bytes to encode
|
|
22
|
+
* @returns Base58-encoded string
|
|
23
|
+
*/
|
|
24
|
+
export function base58Encode(bytes: Uint8Array): string {
|
|
25
|
+
if (bytes.length === 0) return '';
|
|
26
|
+
|
|
27
|
+
// Convert bytes to big integer
|
|
28
|
+
let num = BigInt(0);
|
|
29
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
30
|
+
num = num * BigInt(256) + BigInt(bytes[i]);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Convert to base58
|
|
34
|
+
let result = '';
|
|
35
|
+
while (num > 0) {
|
|
36
|
+
result = ALPHABET[Number(num % BigInt(58))] + result;
|
|
37
|
+
num = num / BigInt(58);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Add leading zeros (encoded as '1' in base58)
|
|
41
|
+
for (let i = 0; i < bytes.length && bytes[i] === 0; i++) {
|
|
42
|
+
result = '1' + result;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Decode Base58 (Bitcoin alphabet) to bytes
|
|
50
|
+
*
|
|
51
|
+
* @param encoded - Base58-encoded string
|
|
52
|
+
* @returns Decoded bytes
|
|
53
|
+
* @throws Error if input contains invalid characters
|
|
54
|
+
*/
|
|
55
|
+
export function base58Decode(encoded: string): Uint8Array {
|
|
56
|
+
if (encoded.length === 0) return new Uint8Array(0);
|
|
57
|
+
|
|
58
|
+
// Convert base58 to big integer
|
|
59
|
+
let num = BigInt(0);
|
|
60
|
+
for (const char of encoded) {
|
|
61
|
+
const value = ALPHABET_MAP.get(char);
|
|
62
|
+
if (value === undefined) {
|
|
63
|
+
throw new Error(`Invalid base58 character: ${char}`);
|
|
64
|
+
}
|
|
65
|
+
num = num * BigInt(58) + BigInt(value);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Convert big integer to bytes
|
|
69
|
+
const bytes: number[] = [];
|
|
70
|
+
while (num > 0) {
|
|
71
|
+
bytes.unshift(Number(num % BigInt(256)));
|
|
72
|
+
num = num / BigInt(256);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Count leading zeros in input (encoded as '1')
|
|
76
|
+
let leadingZeros = 0;
|
|
77
|
+
for (const char of encoded) {
|
|
78
|
+
if (char === '1') {
|
|
79
|
+
leadingZeros++;
|
|
80
|
+
} else {
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Prepend leading zero bytes
|
|
86
|
+
const result = new Uint8Array(leadingZeros + bytes.length);
|
|
87
|
+
// Leading zeros are already 0 in Uint8Array
|
|
88
|
+
result.set(bytes, leadingZeros);
|
|
89
|
+
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Validate a Base58 string
|
|
95
|
+
*
|
|
96
|
+
* @param encoded - String to validate
|
|
97
|
+
* @returns true if valid Base58, false otherwise
|
|
98
|
+
*/
|
|
99
|
+
export function isValidBase58(encoded: string): boolean {
|
|
100
|
+
if (encoded.length === 0) return true;
|
|
101
|
+
|
|
102
|
+
for (const char of encoded) {
|
|
103
|
+
if (!ALPHABET_MAP.has(char)) {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base64URL Encoding/Decoding Utilities
|
|
3
|
+
*
|
|
4
|
+
* Environment-aware base64url helpers that work in both Node.js and Cloudflare Workers.
|
|
5
|
+
* Uses Buffer in Node.js, TextEncoder/Decoder fallback for Workers.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Decode base64url string to string
|
|
10
|
+
*/
|
|
11
|
+
export function base64urlDecodeToString(input: string): string {
|
|
12
|
+
const padded = addPadding(input);
|
|
13
|
+
const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
|
|
14
|
+
|
|
15
|
+
// Prefer Buffer when available (Node.js) as it handles UTF-8 correctly
|
|
16
|
+
if (typeof Buffer !== "undefined") {
|
|
17
|
+
// Buffer.from doesn't throw for invalid base64, so we validate first
|
|
18
|
+
const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
19
|
+
if (!base64Regex.test(base64)) {
|
|
20
|
+
throw new Error("Invalid base64url string: contains invalid characters");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
const decoded = Buffer.from(base64, "base64").toString("utf-8");
|
|
25
|
+
return decoded;
|
|
26
|
+
} catch (error) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
`Invalid base64url string: ${error instanceof Error ? error.message : String(error)}`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// For platforms that don't have Buffer (e.g., Cloudflare Workers)
|
|
34
|
+
if (typeof atob !== "undefined") {
|
|
35
|
+
try {
|
|
36
|
+
const binaryString = atob(base64);
|
|
37
|
+
// Decode UTF-8 bytes to string
|
|
38
|
+
if (typeof TextDecoder !== "undefined") {
|
|
39
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
40
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
41
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
42
|
+
}
|
|
43
|
+
return new TextDecoder().decode(bytes);
|
|
44
|
+
}
|
|
45
|
+
// Fallback: return binary string as-is (may not handle UTF-8 correctly)
|
|
46
|
+
return binaryString;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
`Invalid base64url string: ${error instanceof Error ? error.message : String(error)}`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
throw new Error("Neither Buffer nor atob is available");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Decode base64url string to Uint8Array
|
|
59
|
+
*/
|
|
60
|
+
export function base64urlDecodeToBytes(input: string): Uint8Array {
|
|
61
|
+
const padded = addPadding(input);
|
|
62
|
+
const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
|
|
63
|
+
|
|
64
|
+
// For platforms that don't have Buffer (e.g., Cloudflare Workers)
|
|
65
|
+
if (typeof atob !== "undefined") {
|
|
66
|
+
try {
|
|
67
|
+
const binaryString = atob(base64);
|
|
68
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
69
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
70
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
71
|
+
}
|
|
72
|
+
return bytes;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Invalid base64url string: ${error instanceof Error ? error.message : String(error)}`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// For Node.js environments - Buffer.from doesn't throw, so we can't validate here
|
|
81
|
+
// The caller should validate the result if needed
|
|
82
|
+
return new Uint8Array(Buffer.from(base64, "base64"));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Encode string to base64url
|
|
87
|
+
*/
|
|
88
|
+
export function base64urlEncodeFromString(input: string): string {
|
|
89
|
+
// Prefer Buffer when available (Node.js) as it handles Unicode correctly
|
|
90
|
+
if (typeof Buffer !== "undefined") {
|
|
91
|
+
const base64 = Buffer.from(input, "utf-8").toString("base64");
|
|
92
|
+
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// For platforms that don't have Buffer (e.g., Cloudflare Workers)
|
|
96
|
+
if (typeof btoa !== "undefined") {
|
|
97
|
+
// btoa doesn't handle Unicode, so we need to encode to UTF-8 bytes first
|
|
98
|
+
try {
|
|
99
|
+
const utf8Bytes = new TextEncoder().encode(input);
|
|
100
|
+
const binaryString = Array.from(utf8Bytes)
|
|
101
|
+
.map((byte) => String.fromCharCode(byte))
|
|
102
|
+
.join("");
|
|
103
|
+
const base64 = btoa(binaryString);
|
|
104
|
+
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
105
|
+
} catch {
|
|
106
|
+
// Fallback: if TextEncoder not available, try direct btoa (may fail for Unicode)
|
|
107
|
+
const base64 = btoa(input);
|
|
108
|
+
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
throw new Error("Neither Buffer nor btoa is available");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Encode Uint8Array to base64url
|
|
117
|
+
*/
|
|
118
|
+
export function base64urlEncodeFromBytes(bytes: Uint8Array): string {
|
|
119
|
+
// For platforms that don't have Buffer
|
|
120
|
+
if (typeof btoa !== "undefined") {
|
|
121
|
+
const binaryString = Array.from(bytes)
|
|
122
|
+
.map((byte) => String.fromCharCode(byte))
|
|
123
|
+
.join("");
|
|
124
|
+
const base64 = btoa(binaryString);
|
|
125
|
+
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// For Node.js environments
|
|
129
|
+
const base64 = Buffer.from(bytes).toString("base64");
|
|
130
|
+
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Convert bytes to standard base64 (not base64url)
|
|
135
|
+
*/
|
|
136
|
+
export function bytesToBase64(bytes: Uint8Array): string {
|
|
137
|
+
// For platforms that don't have Buffer
|
|
138
|
+
if (typeof btoa !== "undefined") {
|
|
139
|
+
const binaryString = Array.from(bytes)
|
|
140
|
+
.map((byte) => String.fromCharCode(byte))
|
|
141
|
+
.join("");
|
|
142
|
+
return btoa(binaryString);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// For Node.js environments
|
|
146
|
+
return Buffer.from(bytes).toString("base64");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Convert standard base64 or base64url to bytes
|
|
151
|
+
* Handles both standard base64 (+/) and base64url (-_) formats
|
|
152
|
+
*/
|
|
153
|
+
export function base64ToBytes(base64: string): Uint8Array {
|
|
154
|
+
// Convert base64url to standard base64 if needed
|
|
155
|
+
// Base64url uses - instead of + and _ instead of /
|
|
156
|
+
let standardBase64 = base64.replace(/-/g, "+").replace(/_/g, "/");
|
|
157
|
+
|
|
158
|
+
// Add padding if needed (base64url often omits padding)
|
|
159
|
+
const paddingNeeded = (4 - (standardBase64.length % 4)) % 4;
|
|
160
|
+
standardBase64 += "=".repeat(paddingNeeded);
|
|
161
|
+
|
|
162
|
+
// For platforms that don't have Buffer
|
|
163
|
+
if (typeof atob !== "undefined") {
|
|
164
|
+
const binaryString = atob(standardBase64);
|
|
165
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
166
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
167
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
168
|
+
}
|
|
169
|
+
return bytes;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// For Node.js environments
|
|
173
|
+
return new Uint8Array(Buffer.from(standardBase64, "base64"));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Add padding to base64url string if needed
|
|
178
|
+
*/
|
|
179
|
+
function addPadding(input: string): string {
|
|
180
|
+
const remainder = input.length % 4;
|
|
181
|
+
if (remainder === 0) {
|
|
182
|
+
return input;
|
|
183
|
+
}
|
|
184
|
+
return input + "=".repeat((4 - remainder) % 4);
|
|
185
|
+
}
|