@etherplay/connect-core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,29 @@
1
1
  import { HDKey } from '@scure/bip32';
2
2
  import type { AccountGenerator } from '@etherplay/wallet-connector';
3
- import type { AuthMechanism, EtherplayAccount, OriginAccount } from './types.js';
3
+ import type { AuthMechanism, EtherplayAccount, OriginAccount, PermissionOutcome } from './types.js';
4
4
  export declare function originKeyMessage(orig: string): string;
5
5
  export declare function localKeyMessage(): string;
6
6
  export declare function originPublicKeyPublicationMessage(orig: string, publicKey: `0x${string}`): string;
7
+ export { delegationMessage, delegationDigest, DELEGATION_ABI, type DelegationTerms } from '@etherplay/delegation';
7
8
  export declare function fromEntropyKeyToMnemonic(entropyKey: `0x${string}`): string;
8
9
  export declare function fromSignatureToKey(signature: `0x${string}`): `0x${string}`;
9
10
  export declare function fromMnemonicToHDKey(mnemonic: string, index: number): HDKey;
10
11
  export declare function deriveEtherplayAccount(key: `0x${string}`, mechanism: AuthMechanism, accountGenerator: AccountGenerator): EtherplayAccount;
11
- export declare function deriveOriginAccount(origin: string, account: EtherplayAccount, accountGenerator: AccountGenerator): Promise<OriginAccount>;
12
+ /**
13
+ * Derive the origin account, and mint the credentials that were granted along with it.
14
+ *
15
+ * `delegations` is what to sign, one per (chainId, contract) the host resolved as granted. Nothing
16
+ * is signed for anything absent from it: a credential nobody approved must not exist, and this is
17
+ * the only place that decides what does.
18
+ */
19
+ export declare function deriveOriginAccount(origin: string, account: EtherplayAccount, accountGenerator: AccountGenerator, granted?: {
20
+ delegations?: {
21
+ chainId: number;
22
+ contract: `0x${string}`;
23
+ deadline: number;
24
+ }[];
25
+ permissions?: PermissionOutcome[];
26
+ }): Promise<OriginAccount>;
12
27
  export declare function strip0x(hex: string): string;
13
28
  export declare function add0x(hex: string): string;
14
29
  export declare function astr(str: unknown): void;
@@ -21,4 +36,5 @@ export declare function fromPublicKey(key: string | Uint8Array): string;
21
36
  export declare function fromPrivateKey(key: string | Uint8Array): string;
22
37
  export type * from './types.js';
23
38
  export * from './crypto.js';
39
+ export * from './permissions.js';
24
40
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,KAAK,EAAC,MAAM,cAAc,CAAC;AAGnC,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EAAC,aAAa,EAAE,gBAAgB,EAAE,aAAa,EAAC,MAAM,YAAY,CAAC;AAE/E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAErD;AACD,wBAAgB,eAAe,IAAI,MAAM,CAExC;AACD,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,MAAM,EAAE,GAAG,MAAM,CAEhG;AAED,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,KAAK,MAAM,EAAE,GAAG,MAAM,CAE1E;AAED,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,KAAK,MAAM,EAAE,GAAG,KAAK,MAAM,EAAE,CAG1E;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAI1E;AAED,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,KAAK,MAAM,EAAE,EAClB,SAAS,EAAE,aAAa,EACxB,gBAAgB,EAAE,gBAAgB,GAChC,gBAAgB,CAalB;AAED,wBAAsB,mBAAmB,CACxC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,EACzB,gBAAgB,EAAE,gBAAgB,GAChC,OAAO,CAAC,aAAa,CAAC,CA6BxB;AAMD,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE3C;AACD,wBAAg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,GAAG,KAAK,CAI1E;AAED,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,KAAK,MAAM,EAAE,EAClB,SAAS,EAAE,aAAa,EACxB,gBAAgB,EAAE,gBAAgB,GAChC,gBAAgB,CAalB;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACxC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,EACzB,gBAAgB,EAAE,gBAAgB,EAClC,OAAO,CAAC,EAAE;IACT,WAAW,CAAC,EAAE;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,KAAK,MAAM,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAC,EAAE,CAAC;IAC7E,WAAW,CAAC,EAAE,iBAAiB,EAAE,CAAC;CAClC,GACC,OAAO,CAAC,aAAa,CAAC,CA0DxB;AAMD,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE3C;AACD,wBAAgB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEzC;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,OAAO,QAEhC;AAGD,wBAAgB,KAAK,CAAC,OAAO,EAAE,MAAM;;;EAUpC;AAED,wBAAgB,WAAW,CAAC,qBAAqB,EAAE,MAAM,GAAG,MAAM,CAUjE;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAK9D;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAG/D;AAGD,mBAAmB,YAAY,CAAC;AAChC,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { wordlist } from '@scure/bip39/wordlists/english';
4
4
  import { HDKey } from '@scure/bip32';
5
5
  import { keccak_256 } from '@noble/hashes/sha3';
6
6
  import { secp256k1 } from '@noble/curves/secp256k1';
7
+ import { delegationMessage } from '@etherplay/delegation';
7
8
  export function originKeyMessage(orig) {
8
9
  return `Origin: ${orig}\n\nIMPORTANT: Only sign on trusted websites.\n\nThis grants access to your private session account.\n\nVerify before proceeding.`;
9
10
  }
@@ -13,6 +14,12 @@ export function localKeyMessage() {
13
14
  export function originPublicKeyPublicationMessage(orig, publicKey) {
14
15
  return `Origin: ${orig}\n\nIMPORTANT: Only sign on trusted websites.\n\nThis authorizes the following Public Key to represent your account:\n\n${publicKey}\n\nOthers can use this key to write encrypted messages to you securely.`;
15
16
  }
17
+ // The delegation message is NOT defined here any more. It is consensus between three
18
+ // implementations - the verifying contract, this one, and any third-party wallet - so it lives in
19
+ // @etherplay/delegation next to the Solidity that verifies it and the vectors that pin the two
20
+ // together, where a change to either side fails a test instead of silently invalidating every
21
+ // signature ever generated. Re-exported so callers have one import for the whole feature.
22
+ export { delegationMessage, delegationDigest, DELEGATION_ABI } from '@etherplay/delegation';
16
23
  export function fromEntropyKeyToMnemonic(entropyKey) {
17
24
  return entropyToMnemonic(hexToBytes(entropyKey.slice(2)), wordlist);
18
25
  }
@@ -39,7 +46,14 @@ export function deriveEtherplayAccount(key, mechanism, accountGenerator) {
39
46
  accountType: accountGenerator.type,
40
47
  };
41
48
  }
42
- export async function deriveOriginAccount(origin, account, accountGenerator) {
49
+ /**
50
+ * Derive the origin account, and mint the credentials that were granted along with it.
51
+ *
52
+ * `delegations` is what to sign, one per (chainId, contract) the host resolved as granted. Nothing
53
+ * is signed for anything absent from it: a credential nobody approved must not exist, and this is
54
+ * the only place that decides what does.
55
+ */
56
+ export async function deriveOriginAccount(origin, account, accountGenerator, granted) {
43
57
  const accountMnemonic = fromEntropyKeyToMnemonic(account.localAccount.key);
44
58
  const accountObject = accountGenerator.fromMnemonicToAccount(accountMnemonic, account.localAccount.index);
45
59
  const originKeySignature = await accountGenerator.signTextMessage(originKeyMessage(origin), accountObject.privateKey);
@@ -47,6 +61,29 @@ export async function deriveOriginAccount(origin, account, accountGenerator) {
47
61
  const originMnemonic = fromEntropyKeyToMnemonic(originKey);
48
62
  const originAccount = accountGenerator.fromMnemonicToAccount(originMnemonic, 0);
49
63
  const savedPublicKeyPublicationSignature = await accountGenerator.signTextMessage(originPublicKeyPublicationMessage(origin, originAccount.publicKey), accountObject.privateKey);
64
+ // Pre-generated because a hosted account holds its key at the wallet host and exposes no live
65
+ // arbitrary-signing capability: sign-in is the only moment these can be produced. One per
66
+ // (chainId, contract), because that pair is the whole extent of what each one authorizes, and
67
+ // each carries the deadline it was signed with rather than being open-ended.
68
+ //
69
+ // Signed by the ACCOUNT key, delegating to the origin signer: exactly the claim the contract
70
+ // verifies, which is "account A allows signer S to act for it, here".
71
+ const savedDelegations = [];
72
+ for (const delegation of granted?.delegations || []) {
73
+ const signature = await accountGenerator.signTextMessage(delegationMessage({
74
+ delegate: originAccount.address,
75
+ contract: delegation.contract,
76
+ chainId: delegation.chainId,
77
+ deadline: delegation.deadline,
78
+ }), accountObject.privateKey);
79
+ savedDelegations.push({
80
+ chainId: delegation.chainId,
81
+ contract: delegation.contract,
82
+ delegate: originAccount.address,
83
+ deadline: delegation.deadline,
84
+ signature,
85
+ });
86
+ }
50
87
  return {
51
88
  address: account.localAccount.address,
52
89
  signer: {
@@ -59,6 +96,8 @@ export async function deriveOriginAccount(origin, account, accountGenerator) {
59
96
  metadata: {},
60
97
  mechanismUsed: account.signer.mechanismUsed,
61
98
  savedPublicKeyPublicationSignature,
99
+ savedDelegations,
100
+ permissions: granted?.permissions,
62
101
  accountType: accountGenerator.type,
63
102
  };
64
103
  }
@@ -112,4 +151,5 @@ export function fromPrivateKey(key) {
112
151
  return fromPublicKey(secp256k1.getPublicKey(key, false));
113
152
  }
114
153
  export * from './crypto.js';
154
+ export * from './permissions.js';
115
155
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,iBAAiB,EAAE,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AAC,EAAE,CAAC,CAAC,CAAC,CAAC,eAAe;AAClE,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAwB;IACtD,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAChD,OAAO,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;AAC1D,CAAC;AAID,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC"}
@@ -0,0 +1,101 @@
1
+ import type { PermissionOutcome, PermissionRequest, SavedDelegation } from './types.js';
2
+ /**
3
+ * Turn whatever the app sent into a closed set of requests.
4
+ *
5
+ * Parsing is where the "never dropped" rule is enforced, so it happens ONCE, at the boundary, and
6
+ * everything downstream works with a union it can exhaustively handle. An entry this wallet does
7
+ * not recognise becomes `{type: 'unrecognized'}` carrying the type it asked for, so the UI can name
8
+ * it and the app can be told it was refused rather than ignored.
9
+ *
10
+ * Malformed entries are unrecognized too, not errors: an app that sends a delegation request with
11
+ * no contract has asked for something this wallet cannot act on, which is the same situation as an
12
+ * unknown type and deserves the same visible refusal. Throwing here would fail the whole sign-in
13
+ * over one bad entry.
14
+ */
15
+ export declare function parsePermissionRequests(input: unknown): PermissionRequest[];
16
+ export declare function isRecognizedPermissionType(type: string): boolean;
17
+ /**
18
+ * A request the host decides on its own, with no prompt.
19
+ *
20
+ * Auto-signing does not create authority, it removes a prompt exactly where the prompt was
21
+ * worthless. An origin the host has allowlisted for a contract can already derive this account's
22
+ * signer silently, because the origin mechanism grants that unconditionally, so auto-signing a
23
+ * delegation bounded to that origin's own contract adds nothing an attacker who compromised that
24
+ * origin did not already have, minus one click-through. The prompt is kept for the case that
25
+ * carries information: an origin asking for a contract that is not its own.
26
+ */
27
+ export type AllowlistLookup = (request: {
28
+ chainId: number;
29
+ contract: `0x${string}`;
30
+ }) => boolean;
31
+ /** One (chain, contract) pair: the whole extent of what a delegation authorises. */
32
+ export type DelegationTarget = {
33
+ chainId: number;
34
+ contract: `0x${string}`;
35
+ };
36
+ /**
37
+ * Build the lookup {@link resolvePermissions} takes, from a host's hardcoded table.
38
+ *
39
+ * The comparison lives here rather than in the host because of what it decides: a match means a
40
+ * credential is minted with nobody in the loop. Too loose and the wrong contract gets one silently.
41
+ * The chain is compared exactly, since the same address on another chain is another contract
42
+ * entirely; the address is compared case-insensitively, since EIP-55 spelling is presentation and
43
+ * a table maintained by hand will not be consistent about it.
44
+ */
45
+ export declare function allowlistLookup(entries: DelegationTarget[]): AllowlistLookup;
46
+ /**
47
+ * A deadline `lifetimeSeconds` from now, in UNIX SECONDS.
48
+ *
49
+ * Trivial, and here rather than inline for the one bug it prevents: a millisecond value reaching
50
+ * the signed message produces a credential that expires in the year 57000, which is indistinguishable
51
+ * from no deadline at all and defeats the reason auto-signed credentials carry one.
52
+ */
53
+ export declare function deadlineIn(lifetimeSeconds: number, now?: number): number;
54
+ export type PermissionResolution = {
55
+ /** decided without asking: allowlisted grants, and refusals nobody can consent their way out of */
56
+ settled: PermissionOutcome[];
57
+ /** what is left for the human, in the order the app asked for it */
58
+ pending: PermissionRequest[];
59
+ };
60
+ /**
61
+ * Split the requests into what the host decides itself and what the user must be asked.
62
+ *
63
+ * Kept out of the UI on purpose: which requests get auto-signed and which are refused outright is
64
+ * the security-carrying part of this feature, and it belongs somewhere a test can reach without
65
+ * rendering a component.
66
+ */
67
+ export declare function resolvePermissions(requests: PermissionRequest[], options: {
68
+ isAllowlisted: AllowlistLookup;
69
+ deadline: number;
70
+ }): PermissionResolution;
71
+ /**
72
+ * Whether sign-in can complete with these outcomes.
73
+ *
74
+ * A required entry that is denied fails sign-in; an optional one lets it proceed with that
75
+ * credential missing. The distinction is the app's to make and the host's to honour.
76
+ */
77
+ export declare function deniedRequiredPermissions(outcomes: PermissionOutcome[]): PermissionOutcome[];
78
+ /**
79
+ * The delegations to mint, in the order they were asked for.
80
+ *
81
+ * Only granted delegation entries produce a credential. Everything else reaches the app as an
82
+ * outcome with a reason, which is the point: an app has to tell "you declined" from "nobody asked"
83
+ * to offer the right remedy, and an absent credential says neither.
84
+ */
85
+ export declare function delegationsToSign(outcomes: PermissionOutcome[]): {
86
+ chainId: number;
87
+ contract: `0x${string}`;
88
+ deadline: number;
89
+ }[];
90
+ /**
91
+ * Find the credential for a (chainId, contract) pair.
92
+ *
93
+ * The lookup an app performs every time it wants to act, so it is written once here rather than in
94
+ * each app. Comparison is case-insensitive on the contract because an app that stores a
95
+ * checksummed address should not silently miss a record stored lowercase.
96
+ */
97
+ export declare function findSavedDelegation(delegations: SavedDelegation[] | undefined, target: {
98
+ chainId: number;
99
+ contract: `0x${string}`;
100
+ }): SavedDelegation | undefined;
101
+ //# sourceMappingURL=permissions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions.d.ts","sourceRoot":"","sources":["../src/permissions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,iBAAiB,EAAE,iBAAiB,EAAE,eAAe,EAAC,MAAM,YAAY,CAAC;AAUtF;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,EAAE,CAmC3E;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,KAAK,MAAM,EAAE,CAAA;CAAC,KAAK,OAAO,CAAC;AAE/F,oFAAoF;AACpF,MAAM,MAAM,gBAAgB,GAAG;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,KAAK,MAAM,EAAE,CAAA;CAAC,CAAC;AAE1E;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG,eAAe,CAM5E;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,eAAe,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,MAAM,CAEpF;AAED,MAAM,MAAM,oBAAoB,GAAG;IAClC,mGAAmG;IACnG,OAAO,EAAE,iBAAiB,EAAE,CAAC;IAC7B,oEAAoE;IACpE,OAAO,EAAE,iBAAiB,EAAE,CAAC;CAC7B,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CACjC,QAAQ,EAAE,iBAAiB,EAAE,EAC7B,OAAO,EAAE;IAAC,aAAa,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAC,GACzD,oBAAoB,CAsBtB;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG,iBAAiB,EAAE,CAE5F;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG;IACjE,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,KAAK,MAAM,EAAE,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;CACjB,EAAE,CAYF;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAClC,WAAW,EAAE,eAAe,EAAE,GAAG,SAAS,EAC1C,MAAM,EAAE;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,KAAK,MAAM,EAAE,CAAA;CAAC,GAChD,eAAe,GAAG,SAAS,CAK7B"}
@@ -0,0 +1,148 @@
1
+ /**
2
+ * What the wallet knows how to grant. Anything else is a permission this wallet does not
3
+ * understand, and the one thing that must never happen to it is being dropped quietly: a silent
4
+ * drop is how an old host and a new app end up disagreeing about what was granted, with the app
5
+ * believing it holds something it does not.
6
+ */
7
+ const RECOGNIZED_TYPES = ['delegation'];
8
+ /**
9
+ * Turn whatever the app sent into a closed set of requests.
10
+ *
11
+ * Parsing is where the "never dropped" rule is enforced, so it happens ONCE, at the boundary, and
12
+ * everything downstream works with a union it can exhaustively handle. An entry this wallet does
13
+ * not recognise becomes `{type: 'unrecognized'}` carrying the type it asked for, so the UI can name
14
+ * it and the app can be told it was refused rather than ignored.
15
+ *
16
+ * Malformed entries are unrecognized too, not errors: an app that sends a delegation request with
17
+ * no contract has asked for something this wallet cannot act on, which is the same situation as an
18
+ * unknown type and deserves the same visible refusal. Throwing here would fail the whole sign-in
19
+ * over one bad entry.
20
+ */
21
+ export function parsePermissionRequests(input) {
22
+ if (!Array.isArray(input)) {
23
+ return [];
24
+ }
25
+ return input.map((entry) => {
26
+ const required = !!(entry && typeof entry === 'object' && entry.required === true);
27
+ const type = entry && typeof entry === 'object' ? entry.type : undefined;
28
+ if (type === 'delegation') {
29
+ const { chainId, contract } = entry;
30
+ const chainIdNumber = typeof chainId === 'string' ? Number(chainId) : chainId;
31
+ if (typeof chainIdNumber === 'number' &&
32
+ Number.isSafeInteger(chainIdNumber) &&
33
+ chainIdNumber > 0 &&
34
+ typeof contract === 'string' &&
35
+ /^0x[0-9a-fA-F]{40}$/.test(contract)) {
36
+ return {
37
+ type: 'delegation',
38
+ required,
39
+ chainId: chainIdNumber,
40
+ // Lowercased once, here, so the allowlist comparison, the signed message and the
41
+ // stored record cannot disagree about the spelling of the same address.
42
+ contract: contract.toLowerCase(),
43
+ };
44
+ }
45
+ }
46
+ return {
47
+ type: 'unrecognized',
48
+ required,
49
+ requestedType: typeof type === 'string' ? type : String(type),
50
+ };
51
+ });
52
+ }
53
+ export function isRecognizedPermissionType(type) {
54
+ return RECOGNIZED_TYPES.includes(type);
55
+ }
56
+ /**
57
+ * Build the lookup {@link resolvePermissions} takes, from a host's hardcoded table.
58
+ *
59
+ * The comparison lives here rather than in the host because of what it decides: a match means a
60
+ * credential is minted with nobody in the loop. Too loose and the wrong contract gets one silently.
61
+ * The chain is compared exactly, since the same address on another chain is another contract
62
+ * entirely; the address is compared case-insensitively, since EIP-55 spelling is presentation and
63
+ * a table maintained by hand will not be consistent about it.
64
+ */
65
+ export function allowlistLookup(entries) {
66
+ const normalised = entries.map((entry) => ({ chainId: entry.chainId, contract: entry.contract.toLowerCase() }));
67
+ return (request) => {
68
+ const contract = request.contract.toLowerCase();
69
+ return normalised.some((entry) => entry.chainId === request.chainId && entry.contract === contract);
70
+ };
71
+ }
72
+ /**
73
+ * A deadline `lifetimeSeconds` from now, in UNIX SECONDS.
74
+ *
75
+ * Trivial, and here rather than inline for the one bug it prevents: a millisecond value reaching
76
+ * the signed message produces a credential that expires in the year 57000, which is indistinguishable
77
+ * from no deadline at all and defeats the reason auto-signed credentials carry one.
78
+ */
79
+ export function deadlineIn(lifetimeSeconds, now = Date.now()) {
80
+ return Math.floor(now / 1000) + lifetimeSeconds;
81
+ }
82
+ /**
83
+ * Split the requests into what the host decides itself and what the user must be asked.
84
+ *
85
+ * Kept out of the UI on purpose: which requests get auto-signed and which are refused outright is
86
+ * the security-carrying part of this feature, and it belongs somewhere a test can reach without
87
+ * rendering a component.
88
+ */
89
+ export function resolvePermissions(requests, options) {
90
+ const settled = [];
91
+ const pending = [];
92
+ for (const request of requests) {
93
+ if (request.type === 'unrecognized') {
94
+ // Refused without asking, because there is nothing to ask: a user cannot meaningfully
95
+ // consent to a capability the wallet cannot describe, and pretending otherwise would be
96
+ // the worst kind of consent theatre. Reported, though, never dropped.
97
+ settled.push({ request, granted: false, reason: 'unsupported' });
98
+ continue;
99
+ }
100
+ if (options.isAllowlisted({ chainId: request.chainId, contract: request.contract })) {
101
+ settled.push({ request, granted: true, deadline: options.deadline });
102
+ continue;
103
+ }
104
+ pending.push(request);
105
+ }
106
+ return { settled, pending };
107
+ }
108
+ /**
109
+ * Whether sign-in can complete with these outcomes.
110
+ *
111
+ * A required entry that is denied fails sign-in; an optional one lets it proceed with that
112
+ * credential missing. The distinction is the app's to make and the host's to honour.
113
+ */
114
+ export function deniedRequiredPermissions(outcomes) {
115
+ return outcomes.filter((outcome) => !outcome.granted && outcome.request.required);
116
+ }
117
+ /**
118
+ * The delegations to mint, in the order they were asked for.
119
+ *
120
+ * Only granted delegation entries produce a credential. Everything else reaches the app as an
121
+ * outcome with a reason, which is the point: an app has to tell "you declined" from "nobody asked"
122
+ * to offer the right remedy, and an absent credential says neither.
123
+ */
124
+ export function delegationsToSign(outcomes) {
125
+ const toSign = [];
126
+ for (const outcome of outcomes) {
127
+ if (outcome.granted && outcome.request.type === 'delegation') {
128
+ toSign.push({
129
+ chainId: outcome.request.chainId,
130
+ contract: outcome.request.contract,
131
+ deadline: outcome.deadline,
132
+ });
133
+ }
134
+ }
135
+ return toSign;
136
+ }
137
+ /**
138
+ * Find the credential for a (chainId, contract) pair.
139
+ *
140
+ * The lookup an app performs every time it wants to act, so it is written once here rather than in
141
+ * each app. Comparison is case-insensitive on the contract because an app that stores a
142
+ * checksummed address should not silently miss a record stored lowercase.
143
+ */
144
+ export function findSavedDelegation(delegations, target) {
145
+ const contract = target.contract.toLowerCase();
146
+ return (delegations || []).find((delegation) => delegation.chainId === target.chainId && delegation.contract.toLowerCase() === contract);
147
+ }
148
+ //# sourceMappingURL=permissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions.js","sourceRoot":"","sources":["../src/permissions.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,gBAAgB,GAAG,CAAC,YAAY,CAAU,CAAC;AAEjD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAAc;IACrD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAqB,EAAE;QAC7C,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAK,KAA8B,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC;QAC7G,MAAM,IAAI,GAAG,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ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export type AuthMechanism = EmailMechanism<string | undefined> | OauthMechanism | MnemonicMechanism<number | undefined>;
24
+ /**
25
+ * Authority to act for this account onchain, at ONE contract on ONE chain.
26
+ *
27
+ * The pair is the whole of it: the contract's own address is inside the signed bytes, so a
28
+ * credential granted here is worth nothing anywhere else. See @etherplay/delegation.
29
+ */
30
+ export type DelegationPermissionRequest = {
31
+ type: 'delegation';
32
+ required: boolean;
33
+ chainId: number;
34
+ contract: `0x${string}`;
35
+ };
36
+ /**
37
+ * Something the app asked for that this wallet cannot describe, let alone grant.
38
+ *
39
+ * It exists as a case rather than as a gap because the alternative is dropping it, and a dropped
40
+ * request is how an old host and a new app end up disagreeing about what was granted. It is always
41
+ * denied, and always shown and reported as "this site asked for something this wallet does not
42
+ * understand".
43
+ */
44
+ export type UnrecognizedPermissionRequest = {
45
+ type: 'unrecognized';
46
+ required: boolean;
47
+ /** what the app called it, kept so the UI and the app can both name it */
48
+ requestedType: string;
49
+ };
50
+ /** Declared by the app at connect time. `required` denied fails sign-in; optional does not. */
51
+ export type PermissionRequest = DelegationPermissionRequest | UnrecognizedPermissionRequest;
52
+ /**
53
+ * Everything that must be settled before a signed-in result may be handed to the opener.
54
+ *
55
+ * Approval is enforced by WITHHOLDING THE RESULT, not by asking the app to behave: the app does not
56
+ * receive the thing, rather than receiving it with a flag it is trusted to respect.
57
+ */
58
+ export type OriginApprovalRequest = {
59
+ windowOrigin: string;
60
+ signingOrigin: string;
61
+ /** the account-access gate: this window is not the origin being signed for */
62
+ requestingAccess: boolean;
63
+ /** what the app declared at connect time; empty when it asked for nothing */
64
+ permissions: PermissionRequest[];
65
+ };
66
+ /**
67
+ * The answer to one request, and it is an ANSWER rather than an absence.
68
+ *
69
+ * A denial has to be reported, not merely reflected in a missing credential, because an app cannot
70
+ * tell "you declined" from "nobody asked" without being told, and the two call for different
71
+ * remedies: one is a re-prompt, the other is a misconfiguration the app should say so about.
72
+ */
73
+ export type PermissionOutcome = {
74
+ request: PermissionRequest;
75
+ granted: true;
76
+ /** unix seconds the credential stops being registrable; 0 means no expiry */
77
+ deadline: number;
78
+ } | {
79
+ request: PermissionRequest;
80
+ granted: false;
81
+ /**
82
+ * `denied`: a human said no.
83
+ * `unsupported`: this wallet does not understand the request, so nobody was asked.
84
+ */
85
+ reason: 'denied' | 'unsupported';
86
+ };
87
+ /**
88
+ * A delegation credential, cached from the bytes that were signed.
89
+ *
90
+ * EVERY FIELD HERE IS ALSO INSIDE THE SIGNATURE. They are a cache of it, not metadata beside it, so
91
+ * a stored copy that disagrees with the signed copy cannot be detected locally: the signature
92
+ * simply fails to recover. A failure on the signature path must therefore invalidate this record
93
+ * and ask for a fresh one rather than being reported as a contract error, which makes any
94
+ * disagreement self-healing.
95
+ *
96
+ * `delegate` is redundant today, always being the origin signer, but it makes the record
97
+ * self-describing and catches a mismatch locally instead of onchain.
98
+ */
99
+ export type SavedDelegation = {
100
+ chainId: number;
101
+ contract: `0x${string}`;
102
+ delegate: `0x${string}`;
103
+ /** unix seconds; 0 means no expiry */
104
+ deadline: number;
105
+ signature: `0x${string}`;
106
+ };
24
107
  export type OriginAccount = {
25
108
  address: `0x${string}`;
26
109
  signer: {
@@ -37,6 +120,8 @@ export type OriginAccount = {
37
120
  type: string;
38
121
  };
39
122
  savedPublicKeyPublicationSignature?: `0x${string}`;
123
+ savedDelegations: SavedDelegation[];
124
+ permissions?: PermissionOutcome[];
40
125
  accountType: string;
41
126
  };
42
127
  export type AuthProviderSettings = {
@@ -102,11 +187,7 @@ export type AuthState = {
102
187
  step: 'SignedIn';
103
188
  mechanism: AuthMechanism;
104
189
  account: EtherplayAccount;
105
- requireOriginApproval: false | {
106
- windowOrigin: string;
107
- signingOrigin: string;
108
- requestingAccess: boolean;
109
- };
190
+ requireOriginApproval: false | OriginApprovalRequest;
110
191
  });
111
192
  type Readable<T> = {
112
193
  subscribe(func: (state: T) => void): () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":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AE,EAAE,MAAM,CAAA;CAAC,CAAC;AAEpF,MAAM,WAAW,YAAa,SAAQ,QAAQ,CAAC,SAAS,CAAC;IACxD,IAAI,CAAC,QAAQ,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD,OAAO,CAAC,SAAS,EAAE,aAAa,EAAE,WAAW,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5E,YAAY,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,oBAAoB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACvD,YAAY,CAAC,SAAS,EAAE,cAAc,EAAE,YAAY,EAAE,eAAe,EAAE,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAChH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@etherplay/connect-core",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "core functionality for @etherplay/connect and other",
5
5
  "homepage": "https://github.com/wighawag/etherplay-connect#readme",
6
6
  "repository": {
@@ -33,6 +33,7 @@
33
33
  "@noble/secp256k1": "^2.2.3",
34
34
  "@scure/bip32": "^1.6.2",
35
35
  "@scure/bip39": "^1.5.4",
36
+ "@etherplay/delegation": "0.1.0",
36
37
  "@etherplay/wallet-connector": "0.0.5"
37
38
  },
38
39
  "devDependencies": {
package/src/index.ts CHANGED
@@ -4,8 +4,9 @@ import {wordlist} from '@scure/bip39/wordlists/english';
4
4
  import {HDKey} from '@scure/bip32';
5
5
  import {keccak_256} from '@noble/hashes/sha3';
6
6
  import {secp256k1} from '@noble/curves/secp256k1';
7
+ import {delegationMessage} from '@etherplay/delegation';
7
8
  import type {AccountGenerator} from '@etherplay/wallet-connector';
8
- import type {AuthMechanism, EtherplayAccount, OriginAccount} from './types.js';
9
+ import type {AuthMechanism, EtherplayAccount, OriginAccount, PermissionOutcome, SavedDelegation} from './types.js';
9
10
 
10
11
  export function originKeyMessage(orig: string): string {
11
12
  return `Origin: ${orig}\n\nIMPORTANT: Only sign on trusted websites.\n\nThis grants access to your private session account.\n\nVerify before proceeding.`;
@@ -16,6 +17,12 @@ export function localKeyMessage(): string {
16
17
  export function originPublicKeyPublicationMessage(orig: string, publicKey: `0x${string}`): string {
17
18
  return `Origin: ${orig}\n\nIMPORTANT: Only sign on trusted websites.\n\nThis authorizes the following Public Key to represent your account:\n\n${publicKey}\n\nOthers can use this key to write encrypted messages to you securely.`;
18
19
  }
20
+ // The delegation message is NOT defined here any more. It is consensus between three
21
+ // implementations - the verifying contract, this one, and any third-party wallet - so it lives in
22
+ // @etherplay/delegation next to the Solidity that verifies it and the vectors that pin the two
23
+ // together, where a change to either side fails a test instead of silently invalidating every
24
+ // signature ever generated. Re-exported so callers have one import for the whole feature.
25
+ export {delegationMessage, delegationDigest, DELEGATION_ABI, type DelegationTerms} from '@etherplay/delegation';
19
26
 
20
27
  export function fromEntropyKeyToMnemonic(entropyKey: `0x${string}`): string {
21
28
  return entropyToMnemonic(hexToBytes(entropyKey.slice(2)), wordlist);
@@ -51,10 +58,21 @@ export function deriveEtherplayAccount(
51
58
  };
52
59
  }
53
60
 
61
+ /**
62
+ * Derive the origin account, and mint the credentials that were granted along with it.
63
+ *
64
+ * `delegations` is what to sign, one per (chainId, contract) the host resolved as granted. Nothing
65
+ * is signed for anything absent from it: a credential nobody approved must not exist, and this is
66
+ * the only place that decides what does.
67
+ */
54
68
  export async function deriveOriginAccount(
55
69
  origin: string,
56
70
  account: EtherplayAccount,
57
71
  accountGenerator: AccountGenerator,
72
+ granted?: {
73
+ delegations?: {chainId: number; contract: `0x${string}`; deadline: number}[];
74
+ permissions?: PermissionOutcome[];
75
+ },
58
76
  ): Promise<OriginAccount> {
59
77
  const accountMnemonic = fromEntropyKeyToMnemonic(account.localAccount.key);
60
78
  const accountObject = accountGenerator.fromMnemonicToAccount(accountMnemonic, account.localAccount.index);
@@ -70,6 +88,33 @@ export async function deriveOriginAccount(
70
88
  accountObject.privateKey,
71
89
  );
72
90
 
91
+ // Pre-generated because a hosted account holds its key at the wallet host and exposes no live
92
+ // arbitrary-signing capability: sign-in is the only moment these can be produced. One per
93
+ // (chainId, contract), because that pair is the whole extent of what each one authorizes, and
94
+ // each carries the deadline it was signed with rather than being open-ended.
95
+ //
96
+ // Signed by the ACCOUNT key, delegating to the origin signer: exactly the claim the contract
97
+ // verifies, which is "account A allows signer S to act for it, here".
98
+ const savedDelegations: SavedDelegation[] = [];
99
+ for (const delegation of granted?.delegations || []) {
100
+ const signature = await accountGenerator.signTextMessage(
101
+ delegationMessage({
102
+ delegate: originAccount.address,
103
+ contract: delegation.contract,
104
+ chainId: delegation.chainId,
105
+ deadline: delegation.deadline,
106
+ }),
107
+ accountObject.privateKey,
108
+ );
109
+ savedDelegations.push({
110
+ chainId: delegation.chainId,
111
+ contract: delegation.contract,
112
+ delegate: originAccount.address,
113
+ deadline: delegation.deadline,
114
+ signature,
115
+ });
116
+ }
117
+
73
118
  return {
74
119
  address: account.localAccount.address,
75
120
  signer: {
@@ -82,6 +127,8 @@ export async function deriveOriginAccount(
82
127
  metadata: {},
83
128
  mechanismUsed: account.signer.mechanismUsed,
84
129
  savedPublicKeyPublicationSignature,
130
+ savedDelegations,
131
+ permissions: granted?.permissions,
85
132
  accountType: accountGenerator.type,
86
133
  };
87
134
  }
@@ -141,3 +188,4 @@ export function fromPrivateKey(key: string | Uint8Array): string {
141
188
 
142
189
  export type * from './types.js';
143
190
  export * from './crypto.js';
191
+ export * from './permissions.js';
@@ -0,0 +1,199 @@
1
+ import type {PermissionOutcome, PermissionRequest, SavedDelegation} from './types.js';
2
+
3
+ /**
4
+ * What the wallet knows how to grant. Anything else is a permission this wallet does not
5
+ * understand, and the one thing that must never happen to it is being dropped quietly: a silent
6
+ * drop is how an old host and a new app end up disagreeing about what was granted, with the app
7
+ * believing it holds something it does not.
8
+ */
9
+ const RECOGNIZED_TYPES = ['delegation'] as const;
10
+
11
+ /**
12
+ * Turn whatever the app sent into a closed set of requests.
13
+ *
14
+ * Parsing is where the "never dropped" rule is enforced, so it happens ONCE, at the boundary, and
15
+ * everything downstream works with a union it can exhaustively handle. An entry this wallet does
16
+ * not recognise becomes `{type: 'unrecognized'}` carrying the type it asked for, so the UI can name
17
+ * it and the app can be told it was refused rather than ignored.
18
+ *
19
+ * Malformed entries are unrecognized too, not errors: an app that sends a delegation request with
20
+ * no contract has asked for something this wallet cannot act on, which is the same situation as an
21
+ * unknown type and deserves the same visible refusal. Throwing here would fail the whole sign-in
22
+ * over one bad entry.
23
+ */
24
+ export function parsePermissionRequests(input: unknown): PermissionRequest[] {
25
+ if (!Array.isArray(input)) {
26
+ return [];
27
+ }
28
+ return input.map((entry): PermissionRequest => {
29
+ const required = !!(entry && typeof entry === 'object' && (entry as {required?: unknown}).required === true);
30
+ const type = entry && typeof entry === 'object' ? (entry as {type?: unknown}).type : undefined;
31
+
32
+ if (type === 'delegation') {
33
+ const {chainId, contract} = entry as {chainId?: unknown; contract?: unknown};
34
+ const chainIdNumber = typeof chainId === 'string' ? Number(chainId) : chainId;
35
+ if (
36
+ typeof chainIdNumber === 'number' &&
37
+ Number.isSafeInteger(chainIdNumber) &&
38
+ chainIdNumber > 0 &&
39
+ typeof contract === 'string' &&
40
+ /^0x[0-9a-fA-F]{40}$/.test(contract)
41
+ ) {
42
+ return {
43
+ type: 'delegation',
44
+ required,
45
+ chainId: chainIdNumber,
46
+ // Lowercased once, here, so the allowlist comparison, the signed message and the
47
+ // stored record cannot disagree about the spelling of the same address.
48
+ contract: contract.toLowerCase() as `0x${string}`,
49
+ };
50
+ }
51
+ }
52
+
53
+ return {
54
+ type: 'unrecognized',
55
+ required,
56
+ requestedType: typeof type === 'string' ? type : String(type),
57
+ };
58
+ });
59
+ }
60
+
61
+ export function isRecognizedPermissionType(type: string): boolean {
62
+ return (RECOGNIZED_TYPES as readonly string[]).includes(type);
63
+ }
64
+
65
+ /**
66
+ * A request the host decides on its own, with no prompt.
67
+ *
68
+ * Auto-signing does not create authority, it removes a prompt exactly where the prompt was
69
+ * worthless. An origin the host has allowlisted for a contract can already derive this account's
70
+ * signer silently, because the origin mechanism grants that unconditionally, so auto-signing a
71
+ * delegation bounded to that origin's own contract adds nothing an attacker who compromised that
72
+ * origin did not already have, minus one click-through. The prompt is kept for the case that
73
+ * carries information: an origin asking for a contract that is not its own.
74
+ */
75
+ export type AllowlistLookup = (request: {chainId: number; contract: `0x${string}`}) => boolean;
76
+
77
+ /** One (chain, contract) pair: the whole extent of what a delegation authorises. */
78
+ export type DelegationTarget = {chainId: number; contract: `0x${string}`};
79
+
80
+ /**
81
+ * Build the lookup {@link resolvePermissions} takes, from a host's hardcoded table.
82
+ *
83
+ * The comparison lives here rather than in the host because of what it decides: a match means a
84
+ * credential is minted with nobody in the loop. Too loose and the wrong contract gets one silently.
85
+ * The chain is compared exactly, since the same address on another chain is another contract
86
+ * entirely; the address is compared case-insensitively, since EIP-55 spelling is presentation and
87
+ * a table maintained by hand will not be consistent about it.
88
+ */
89
+ export function allowlistLookup(entries: DelegationTarget[]): AllowlistLookup {
90
+ const normalised = entries.map((entry) => ({chainId: entry.chainId, contract: entry.contract.toLowerCase()}));
91
+ return (request) => {
92
+ const contract = request.contract.toLowerCase();
93
+ return normalised.some((entry) => entry.chainId === request.chainId && entry.contract === contract);
94
+ };
95
+ }
96
+
97
+ /**
98
+ * A deadline `lifetimeSeconds` from now, in UNIX SECONDS.
99
+ *
100
+ * Trivial, and here rather than inline for the one bug it prevents: a millisecond value reaching
101
+ * the signed message produces a credential that expires in the year 57000, which is indistinguishable
102
+ * from no deadline at all and defeats the reason auto-signed credentials carry one.
103
+ */
104
+ export function deadlineIn(lifetimeSeconds: number, now: number = Date.now()): number {
105
+ return Math.floor(now / 1000) + lifetimeSeconds;
106
+ }
107
+
108
+ export type PermissionResolution = {
109
+ /** decided without asking: allowlisted grants, and refusals nobody can consent their way out of */
110
+ settled: PermissionOutcome[];
111
+ /** what is left for the human, in the order the app asked for it */
112
+ pending: PermissionRequest[];
113
+ };
114
+
115
+ /**
116
+ * Split the requests into what the host decides itself and what the user must be asked.
117
+ *
118
+ * Kept out of the UI on purpose: which requests get auto-signed and which are refused outright is
119
+ * the security-carrying part of this feature, and it belongs somewhere a test can reach without
120
+ * rendering a component.
121
+ */
122
+ export function resolvePermissions(
123
+ requests: PermissionRequest[],
124
+ options: {isAllowlisted: AllowlistLookup; deadline: number},
125
+ ): PermissionResolution {
126
+ const settled: PermissionOutcome[] = [];
127
+ const pending: PermissionRequest[] = [];
128
+
129
+ for (const request of requests) {
130
+ if (request.type === 'unrecognized') {
131
+ // Refused without asking, because there is nothing to ask: a user cannot meaningfully
132
+ // consent to a capability the wallet cannot describe, and pretending otherwise would be
133
+ // the worst kind of consent theatre. Reported, though, never dropped.
134
+ settled.push({request, granted: false, reason: 'unsupported'});
135
+ continue;
136
+ }
137
+
138
+ if (options.isAllowlisted({chainId: request.chainId, contract: request.contract})) {
139
+ settled.push({request, granted: true, deadline: options.deadline});
140
+ continue;
141
+ }
142
+
143
+ pending.push(request);
144
+ }
145
+
146
+ return {settled, pending};
147
+ }
148
+
149
+ /**
150
+ * Whether sign-in can complete with these outcomes.
151
+ *
152
+ * A required entry that is denied fails sign-in; an optional one lets it proceed with that
153
+ * credential missing. The distinction is the app's to make and the host's to honour.
154
+ */
155
+ export function deniedRequiredPermissions(outcomes: PermissionOutcome[]): PermissionOutcome[] {
156
+ return outcomes.filter((outcome) => !outcome.granted && outcome.request.required);
157
+ }
158
+
159
+ /**
160
+ * The delegations to mint, in the order they were asked for.
161
+ *
162
+ * Only granted delegation entries produce a credential. Everything else reaches the app as an
163
+ * outcome with a reason, which is the point: an app has to tell "you declined" from "nobody asked"
164
+ * to offer the right remedy, and an absent credential says neither.
165
+ */
166
+ export function delegationsToSign(outcomes: PermissionOutcome[]): {
167
+ chainId: number;
168
+ contract: `0x${string}`;
169
+ deadline: number;
170
+ }[] {
171
+ const toSign: {chainId: number; contract: `0x${string}`; deadline: number}[] = [];
172
+ for (const outcome of outcomes) {
173
+ if (outcome.granted && outcome.request.type === 'delegation') {
174
+ toSign.push({
175
+ chainId: outcome.request.chainId,
176
+ contract: outcome.request.contract,
177
+ deadline: outcome.deadline,
178
+ });
179
+ }
180
+ }
181
+ return toSign;
182
+ }
183
+
184
+ /**
185
+ * Find the credential for a (chainId, contract) pair.
186
+ *
187
+ * The lookup an app performs every time it wants to act, so it is written once here rather than in
188
+ * each app. Comparison is case-insensitive on the contract because an app that stores a
189
+ * checksummed address should not silently miss a record stored lowercase.
190
+ */
191
+ export function findSavedDelegation(
192
+ delegations: SavedDelegation[] | undefined,
193
+ target: {chainId: number; contract: `0x${string}`},
194
+ ): SavedDelegation | undefined {
195
+ const contract = target.contract.toLowerCase();
196
+ return (delegations || []).find(
197
+ (delegation) => delegation.chainId === target.chainId && delegation.contract.toLowerCase() === contract,
198
+ );
199
+ }
package/src/types.ts CHANGED
@@ -18,6 +18,99 @@ export type EmailMechanism<T extends string | undefined> = {
18
18
 
19
19
  export type AuthMechanism = EmailMechanism<string | undefined> | OauthMechanism | MnemonicMechanism<number | undefined>;
20
20
 
21
+ // --- PERMISSIONS
22
+
23
+ /**
24
+ * Authority to act for this account onchain, at ONE contract on ONE chain.
25
+ *
26
+ * The pair is the whole of it: the contract's own address is inside the signed bytes, so a
27
+ * credential granted here is worth nothing anywhere else. See @etherplay/delegation.
28
+ */
29
+ export type DelegationPermissionRequest = {
30
+ type: 'delegation';
31
+ required: boolean;
32
+ chainId: number;
33
+ contract: `0x${string}`;
34
+ };
35
+
36
+ /**
37
+ * Something the app asked for that this wallet cannot describe, let alone grant.
38
+ *
39
+ * It exists as a case rather than as a gap because the alternative is dropping it, and a dropped
40
+ * request is how an old host and a new app end up disagreeing about what was granted. It is always
41
+ * denied, and always shown and reported as "this site asked for something this wallet does not
42
+ * understand".
43
+ */
44
+ export type UnrecognizedPermissionRequest = {
45
+ type: 'unrecognized';
46
+ required: boolean;
47
+ /** what the app called it, kept so the UI and the app can both name it */
48
+ requestedType: string;
49
+ };
50
+
51
+ /** Declared by the app at connect time. `required` denied fails sign-in; optional does not. */
52
+ export type PermissionRequest = DelegationPermissionRequest | UnrecognizedPermissionRequest;
53
+
54
+ /**
55
+ * Everything that must be settled before a signed-in result may be handed to the opener.
56
+ *
57
+ * Approval is enforced by WITHHOLDING THE RESULT, not by asking the app to behave: the app does not
58
+ * receive the thing, rather than receiving it with a flag it is trusted to respect.
59
+ */
60
+ export type OriginApprovalRequest = {
61
+ windowOrigin: string;
62
+ signingOrigin: string;
63
+ /** the account-access gate: this window is not the origin being signed for */
64
+ requestingAccess: boolean;
65
+ /** what the app declared at connect time; empty when it asked for nothing */
66
+ permissions: PermissionRequest[];
67
+ };
68
+
69
+ /**
70
+ * The answer to one request, and it is an ANSWER rather than an absence.
71
+ *
72
+ * A denial has to be reported, not merely reflected in a missing credential, because an app cannot
73
+ * tell "you declined" from "nobody asked" without being told, and the two call for different
74
+ * remedies: one is a re-prompt, the other is a misconfiguration the app should say so about.
75
+ */
76
+ export type PermissionOutcome =
77
+ | {
78
+ request: PermissionRequest;
79
+ granted: true;
80
+ /** unix seconds the credential stops being registrable; 0 means no expiry */
81
+ deadline: number;
82
+ }
83
+ | {
84
+ request: PermissionRequest;
85
+ granted: false;
86
+ /**
87
+ * `denied`: a human said no.
88
+ * `unsupported`: this wallet does not understand the request, so nobody was asked.
89
+ */
90
+ reason: 'denied' | 'unsupported';
91
+ };
92
+
93
+ /**
94
+ * A delegation credential, cached from the bytes that were signed.
95
+ *
96
+ * EVERY FIELD HERE IS ALSO INSIDE THE SIGNATURE. They are a cache of it, not metadata beside it, so
97
+ * a stored copy that disagrees with the signed copy cannot be detected locally: the signature
98
+ * simply fails to recover. A failure on the signature path must therefore invalidate this record
99
+ * and ask for a fresh one rather than being reported as a contract error, which makes any
100
+ * disagreement self-healing.
101
+ *
102
+ * `delegate` is redundant today, always being the origin signer, but it makes the record
103
+ * self-describing and catches a mismatch locally instead of onchain.
104
+ */
105
+ export type SavedDelegation = {
106
+ chainId: number;
107
+ contract: `0x${string}`;
108
+ delegate: `0x${string}`;
109
+ /** unix seconds; 0 means no expiry */
110
+ deadline: number;
111
+ signature: `0x${string}`;
112
+ };
113
+
21
114
  export type OriginAccount = {
22
115
  address: `0x${string}`;
23
116
  signer: {
@@ -32,6 +125,16 @@ export type OriginAccount = {
32
125
  };
33
126
  mechanismUsed: AuthMechanism | {type: string};
34
127
  savedPublicKeyPublicationSignature?: `0x${string}`;
128
+ // Credentials authorizing `signer.address` to act onchain for this account, one per
129
+ // (chainId, contract) the app asked for and the user (or the host's allowlist) granted.
130
+ //
131
+ // A LIST, not a field, because authority is per contract: there is no such thing as "the"
132
+ // delegation. Empty when nothing was asked for or nothing was granted, which is why the
133
+ // outcomes below are the thing to read when an app wants to know WHY it has nothing.
134
+ savedDelegations: SavedDelegation[];
135
+ // The answer to every permission the app requested, granted or not. Present whenever the app
136
+ // asked for anything.
137
+ permissions?: PermissionOutcome[];
35
138
  accountType: string;
36
139
  };
37
140
 
@@ -132,13 +235,10 @@ export type AuthState = {error?: {message: string; cause?: any}} & (
132
235
  step: 'SignedIn';
133
236
  mechanism: AuthMechanism;
134
237
  account: EtherplayAccount;
135
- requireOriginApproval:
136
- | false
137
- | {
138
- windowOrigin: string;
139
- signingOrigin: string;
140
- requestingAccess: boolean;
141
- };
238
+ // What must be settled before the result may be handed to the opener, or `false` when
239
+ // there is nothing to settle. `permissions` extends the existing access gate per entry
240
+ // rather than replacing it.
241
+ requireOriginApproval: false | OriginApprovalRequest;
142
242
  }
143
243
  );
144
244