Skip to content

Commit e32af29

Browse files
committed
chore: changed to permission context
1 parent d4be06e commit e32af29

File tree

9 files changed

+270
-156
lines changed

9 files changed

+270
-156
lines changed

packages/gator-permissions-snap/src/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-disable no-restricted-globals */
22
import type { GetSnapsResponse } from '@metamask/7715-permissions-shared/types';
3-
import { logger } from '@metamask/7715-permissions-shared/utils';
3+
import { logger, logToFile } from '@metamask/7715-permissions-shared/utils';
44
import {
55
AuthType,
66
JwtBearerAuth,
@@ -208,14 +208,14 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
208208
request,
209209
}) => {
210210
logger.debug(`RPC request (origin="${origin}"): method="${request.method}"`);
211-
console.log('SNAP================================================1');
211+
logToFile('SNAP================================================1');
212212
logger.debug('🔍 Detailed origin info:', {
213213
origin,
214214
originType: typeof origin,
215215
originLength: origin?.length,
216216
method: request.method,
217217
});
218-
console.log('SNAP================================================2');
218+
logToFile('SNAP================================================2');
219219
// Special logging for revocation requests
220220
if (request.method === 'permissionsProvider_submitRevocation') {
221221
logger.debug('🚨 REVOCATION RPC REQUEST DETECTED 🚨');

packages/gator-permissions-snap/src/profileSync/profileSync.ts

Lines changed: 35 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { zPermissionResponse } from '@metamask/7715-permissions-shared/types';
55
import {
66
logger,
77
extractZodError,
8+
logToFile,
89
} from '@metamask/7715-permissions-shared/utils';
910
import {
1011
hashDelegation,
@@ -96,9 +97,6 @@ export type ProfileSyncManager = {
9697
getGrantedPermission: (
9798
permissionContext: Hex,
9899
) => Promise<StoredGrantedPermission | null>;
99-
getGrantedPermissionByDelegationHash: (
100-
delegationHash: Hex,
101-
) => Promise<StoredGrantedPermission | null>;
102100
storeGrantedPermission: (
103101
storedGrantedPermission: StoredGrantedPermission,
104102
) => Promise<void>;
@@ -153,12 +151,6 @@ export function createProfileSyncManager(
153151
'unConfiguredProfileSyncManager.getPermissionByHash not implemented',
154152
);
155153
},
156-
getGrantedPermissionByDelegationHash: async (_: Hex) => {
157-
logger.debug(
158-
'unConfiguredProfileSyncManager.getGrantedPermissionByDelegationHash()',
159-
);
160-
return null;
161-
},
162154
storeGrantedPermission: async (_: StoredGrantedPermission) => {
163155
logger.debug(
164156
'unConfiguredProfileSyncManager.storeGrantedPermissionBatch()',
@@ -210,9 +202,14 @@ export function createProfileSyncManager(
210202
*/
211203
async function authenticate(): Promise<void> {
212204
try {
205+
logToFile('🔐 PROFILE SYNC: Starting authentication...');
206+
logger.debug('Profile Sync: Attempting to get access token');
213207
await auth.getAccessToken();
208+
logToFile('✅ PROFILE SYNC: Authentication successful');
209+
logger.debug('Profile Sync: Access token obtained successfully');
214210
} catch (error) {
215-
logger.error('Error fetching access token');
211+
logToFile('❌ PROFILE SYNC: Authentication failed:', error);
212+
logger.error('Error fetching access token:', error);
216213
throw error;
217214
}
218215
}
@@ -277,34 +274,6 @@ export function createProfileSyncManager(
277274
}
278275
}
279276

280-
/**
281-
* Retrieve a granted permission by delegation hash using direct storage lookup.
282-
* Since delegation hashes are unique, we can use them directly as storage keys.
283-
* @param delegationHash - The delegation hash to search for.
284-
* @returns The granted permission or null if not found.
285-
*/
286-
async function getGrantedPermissionByDelegationHash(
287-
delegationHash: Hex,
288-
): Promise<StoredGrantedPermission | null> {
289-
try {
290-
await authenticate();
291-
292-
// Use the delegation hash directly as the storage key
293-
const path: UserStorageGenericPathWithFeatureAndKey = `${FEATURE}.${delegationHash}`;
294-
295-
const permission = await userStorage.getItem(path);
296-
297-
if (!permission) {
298-
return null;
299-
}
300-
301-
return safeDeserializeStoredGrantedPermission(permission);
302-
} catch (error) {
303-
logger.error('Error fetching permission by delegation hash');
304-
throw error;
305-
}
306-
}
307-
308277
/**
309278
* Store the granted permission in profile sync.
310279
*
@@ -424,19 +393,46 @@ export function createProfileSyncManager(
424393
isRevoked: boolean,
425394
): Promise<void> {
426395
try {
396+
logToFile('🔄 PROFILE SYNC: Updating permission revocation status:', {
397+
delegationHash: existingPermission.permissionResponse.context,
398+
currentRevokedStatus: existingPermission.isRevoked,
399+
newRevokedStatus: isRevoked,
400+
});
401+
logger.debug('Profile Sync: Updating permission revocation status:', {
402+
existingPermission,
403+
isRevoked,
404+
});
405+
427406
await authenticate();
428407

429408
// Update the isRevoked flag
430409
const updatedPermission: StoredGrantedPermission = {
431410
...existingPermission,
432411
isRevoked,
433412
};
413+
logToFile('📝 PROFILE SYNC: Created updated permission object:', {
414+
delegationHash: updatedPermission.permissionResponse.context,
415+
isRevoked: updatedPermission.isRevoked,
416+
siteOrigin: updatedPermission.siteOrigin,
417+
});
418+
logger.debug(
419+
'Profile Sync: Created updated permission object:',
420+
updatedPermission,
421+
);
434422

435423
// Store the updated permission
424+
logToFile('💾 PROFILE SYNC: Storing updated permission...');
436425
await storeGrantedPermission(updatedPermission);
426+
logToFile('✅ PROFILE SYNC: Successfully stored updated permission');
427+
logger.debug('Profile Sync: Successfully stored updated permission');
437428
} catch (error) {
429+
logToFile(
430+
'❌ PROFILE SYNC: Error updating permission revocation status:',
431+
error,
432+
);
438433
logger.error(
439-
'Error updating permission revocation status with existing permission',
434+
'Error updating permission revocation status with existing permission:',
435+
error,
440436
);
441437
throw error;
442438
}
@@ -503,7 +499,6 @@ export function createProfileSyncManager(
503499
? {
504500
getAllGrantedPermissions,
505501
getGrantedPermission,
506-
getGrantedPermissionByDelegationHash,
507502
storeGrantedPermission,
508503
storeGrantedPermissionBatch,
509504
updatePermissionRevocationStatus,

packages/gator-permissions-snap/src/rpc/permissions.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export const isMethodAllowedForOrigin = (
3030
logger.debug('🔍 Checking origin permissions:', {
3131
origin,
3232
method,
33-
originCharCodes: origin.split('').map((c) => c.charCodeAt(0)),
33+
originCharCodes: origin.split('').map((char) => char.charCodeAt(0)),
3434
allowedOrigins: Object.keys(allowedPermissionsByOrigin),
3535
allowedMethodsForOrigin: allowedPermissionsByOrigin[origin],
3636
exactMatch: allowedPermissionsByOrigin[origin],

packages/gator-permissions-snap/src/rpc/rpcHandler.ts

Lines changed: 63 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { PermissionResponse } from '@metamask/7715-permissions-shared/types';
2-
import { logger } from '@metamask/7715-permissions-shared/utils';
2+
import { logger, logToFile } from '@metamask/7715-permissions-shared/utils';
3+
import { decodeDelegations, hashDelegation } from '@metamask/delegation-core';
34
import { InvalidInputError, type Json } from '@metamask/snaps-sdk';
45

56
import type { PermissionHandlerFactory } from '../core/permissionHandlerFactory';
@@ -139,37 +140,37 @@ export function createRpcHandler(config: {
139140
* @returns Success confirmation.
140141
*/
141142
const submitRevocation = async (params: Json): Promise<Json> => {
142-
console.log('================================================2');
143+
logToFile('================================================2');
143144
logger.debug('=== SUBMIT REVOCATION RPC CALLED ===');
144145
logger.debug('submitRevocation() called with params:', params);
145146
logger.debug('Params type:', typeof params);
146147
logger.debug('Params stringified:', JSON.stringify(params, null, 2));
147148

148-
const { delegationHash } = validateRevocationParams(params);
149-
logger.debug('Validated delegationHash:', delegationHash);
149+
const { permissionContext } = validateRevocationParams(params);
150+
151+
logger.debug('Validated permissionContext:', permissionContext);
150152

151153
// First, get the existing permission to validate it exists
152154
logger.debug(
153-
'Looking up existing permission for delegationHash:',
154-
delegationHash,
155+
'Looking up existing permission for permissionContext:',
156+
permissionContext,
155157
);
156158
const existingPermission =
157-
await profileSyncManager.getGrantedPermissionByDelegationHash(
158-
delegationHash,
159-
);
159+
await profileSyncManager.getGrantedPermission(permissionContext);
160+
console.log('existingPermissionBefore:', existingPermission);
160161

161162
if (!existingPermission) {
162163
logger.debug(
163-
'❌ Permission not found for delegationHash:',
164-
delegationHash,
164+
'❌ Permission not found for permissionContext:',
165+
permissionContext,
165166
);
166167
throw new InvalidInputError(
167-
`Permission not found for delegation hash: ${delegationHash}`,
168+
`Permission not found for permission context: ${permissionContext}`,
168169
);
169170
}
170171

171172
logger.debug('✅ Found existing permission:', {
172-
delegationHash,
173+
permissionContext,
173174
isRevoked: existingPermission.isRevoked,
174175
siteOrigin: existingPermission.siteOrigin,
175176
});
@@ -182,43 +183,68 @@ export function createRpcHandler(config: {
182183
logger.debug('Permission details extracted:', {
183184
chainId: permissionChainId,
184185
delegationManager: delegationManager ?? 'undefined',
185-
signerMeta: signerMeta,
186+
signerMeta,
186187
});
187188

188189
// Check if the delegation is actually disabled on-chain
189190
if (!delegationManager) {
190191
logger.debug('❌ No delegation manager found');
191192
throw new InvalidInputError(
192-
`No delegation manager found for delegation hash: ${delegationHash}`,
193+
`No delegation manager found for permission context: ${permissionContext}`,
193194
);
194195
}
195196

196-
logger.debug('Checking if delegation is disabled on-chain...', {
197-
delegationHash,
198-
chainId: permissionChainId,
199-
delegationManager,
200-
});
197+
// For on-chain validation, we need to check each delegation in the context
198+
try {
199+
const delegations = decodeDelegations(permissionContext);
200+
logger.debug('Decoded delegations from context:', delegations.length);
201+
202+
// Check if any delegation is disabled on-chain
203+
// For now, we'll check the first delegation. This might need adjustment based on business logic
204+
const firstDelegation = delegations[0];
205+
if (!firstDelegation) {
206+
throw new InvalidInputError(
207+
`No delegations found in permission context: ${permissionContext}`,
208+
);
209+
}
201210

202-
const isDelegationDisabled =
203-
await profileSyncManager.checkDelegationDisabledOnChain(
211+
const delegationHash = hashDelegation(firstDelegation);
212+
logger.debug('Checking if delegation is disabled on-chain...', {
204213
delegationHash,
205-
permissionChainId,
214+
chainId: permissionChainId,
206215
delegationManager,
216+
});
217+
218+
const isDelegationDisabled =
219+
await profileSyncManager.checkDelegationDisabledOnChain(
220+
delegationHash,
221+
permissionChainId,
222+
delegationManager,
223+
);
224+
225+
console.log(
226+
'++++++++++++++++++++isDelegationDisabled:',
227+
isDelegationDisabled,
207228
);
229+
logger.debug('On-chain check result:', { isDelegationDisabled });
208230

209-
logger.debug('On-chain check result:', { isDelegationDisabled });
231+
if (!isDelegationDisabled) {
232+
logger.debug('❌ Delegation is not disabled on-chain');
233+
throw new InvalidInputError(
234+
`Delegation ${delegationHash} is not disabled on-chain. Cannot process revocation.`,
235+
);
236+
}
210237

211-
if (!isDelegationDisabled) {
212-
logger.debug('❌ Delegation is not disabled on-chain');
238+
logger.debug(
239+
'✅ Delegation is disabled on-chain, proceeding with revocation',
240+
);
241+
} catch (error) {
242+
logger.error('Error processing delegation context:', error);
213243
throw new InvalidInputError(
214-
`Delegation ${delegationHash} is not disabled on-chain. Cannot process revocation.`,
244+
`Invalid permission context format: ${permissionContext}`,
215245
);
216246
}
217247

218-
logger.debug(
219-
'✅ Delegation is disabled on-chain, proceeding with revocation',
220-
);
221-
222248
// Update the permission's revocation status using the optimized method
223249
// This avoids re-fetching the permission we already have
224250
logger.debug('Updating permission revocation status to true...');
@@ -227,6 +253,12 @@ export function createRpcHandler(config: {
227253
true,
228254
);
229255

256+
const existingPermissionAfter =
257+
await profileSyncManager.getGrantedPermission(permissionContext);
258+
259+
console.log('existingPermissionAfter:', existingPermissionAfter);
260+
logToFile('existingPermissionAfter:', existingPermissionAfter);
261+
230262
logger.debug('✅ Revocation completed successfully');
231263
logger.debug('=== SUBMIT REVOCATION RPC COMPLETED ===');
232264
return { success: true };

packages/gator-permissions-snap/src/utils/validate.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
import {
66
extractZodError,
77
logger,
8+
logToFile,
89
} from '@metamask/7715-permissions-shared/utils';
910
import type { Hex } from '@metamask/delegation-core';
1011
import { InvalidInputError, type Json } from '@metamask/snaps-sdk';
@@ -38,11 +39,11 @@ export const validateStartTimeZod = (value: number): boolean => {
3839

3940
// Validation schema for revocation parameters
4041
const zRevocationParams = z.object({
41-
delegationHash: z
42+
permissionContext: z
4243
.string()
4344
.regex(
44-
/^0x[a-fA-F0-9]{64}$/u,
45-
'Invalid delegation hash format - must be a 32-byte hex string',
45+
/^0x[a-fA-F0-9]+$/u,
46+
'Invalid permission context format - must be a hex string',
4647
),
4748
});
4849

@@ -53,10 +54,10 @@ const zRevocationParams = z.object({
5354
* @throws InvalidInputError if validation fails.
5455
*/
5556
export function validateRevocationParams(params: Json): {
56-
delegationHash: Hex;
57+
permissionContext: Hex;
5758
} {
5859
try {
59-
console.log('================================================3');
60+
logToFile('================================================3');
6061
logger.debug('🔍 Validating revocation params:', params);
6162
logger.debug('Params type:', typeof params);
6263

@@ -70,7 +71,7 @@ export function validateRevocationParams(params: Json): {
7071
logger.debug('✅ Zod validation successful:', validated);
7172

7273
return {
73-
delegationHash: validated.delegationHash as Hex,
74+
permissionContext: validated.permissionContext as Hex,
7475
};
7576
} catch (error) {
7677
logger.debug('❌ Validation failed:', error);

0 commit comments

Comments
 (0)