@did-plc/lib 0.0.1

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.
@@ -0,0 +1,214 @@
1
+ import { check, cidForCbor } from '@atproto/common'
2
+ import { EcdsaKeypair, Secp256k1Keypair } from '@atproto/crypto'
3
+ import {
4
+ GenesisHashError,
5
+ ImproperOperationError,
6
+ InvalidSignatureError,
7
+ MisorderedOperationError,
8
+ } from '../src'
9
+ import * as data from '../src/data'
10
+ import * as operations from '../src/operations'
11
+ import * as t from '../src/types'
12
+
13
+ describe('plc did data', () => {
14
+ const ops: t.Operation[] = []
15
+
16
+ let signingKey: Secp256k1Keypair
17
+ let rotationKey1: Secp256k1Keypair
18
+ let rotationKey2: EcdsaKeypair
19
+ let did: string
20
+ let handle = 'at://alice.example.com'
21
+ let atpPds = 'https://example.com'
22
+
23
+ let oldRotationKey1: Secp256k1Keypair
24
+
25
+ beforeAll(async () => {
26
+ signingKey = await Secp256k1Keypair.create()
27
+ rotationKey1 = await Secp256k1Keypair.create()
28
+ rotationKey2 = await EcdsaKeypair.create()
29
+ })
30
+
31
+ const lastOp = () => {
32
+ const lastOp = ops.at(-1)
33
+ if (!lastOp) {
34
+ throw new Error('expected an op on log')
35
+ }
36
+ return lastOp
37
+ }
38
+
39
+ const verifyDoc = (doc: t.DocumentData | null) => {
40
+ if (!doc) {
41
+ throw new Error('expected doc')
42
+ }
43
+ expect(doc.did).toEqual(did)
44
+ expect(doc.verificationMethods).toEqual({ atproto: signingKey.did() })
45
+ expect(doc.rotationKeys).toEqual([rotationKey1.did(), rotationKey2.did()])
46
+ expect(doc.alsoKnownAs).toEqual([handle])
47
+ expect(doc.services).toEqual({
48
+ atproto_pds: {
49
+ type: 'AtprotoPersonalDataServer',
50
+ endpoint: atpPds,
51
+ },
52
+ })
53
+ }
54
+
55
+ it('creates a valid create op', async () => {
56
+ const createOp = await operations.atprotoOp({
57
+ signingKey: signingKey.did(),
58
+ rotationKeys: [rotationKey1.did(), rotationKey2.did()],
59
+ handle,
60
+ pds: atpPds,
61
+ prev: null,
62
+ signer: rotationKey1,
63
+ })
64
+ const isValid = check.is(createOp, t.def.operation)
65
+ expect(isValid).toBeTruthy()
66
+ ops.push(createOp)
67
+ did = await operations.didForCreateOp(createOp)
68
+ })
69
+
70
+ it('parses an operation log with no updates', async () => {
71
+ const doc = await data.validateOperationLog(did, ops)
72
+ verifyDoc(doc)
73
+ })
74
+
75
+ it('updates handle', async () => {
76
+ const noPrefix = 'ali.exampl2.com'
77
+ handle = `at://${noPrefix}`
78
+ const op = await operations.updateHandleOp(lastOp(), rotationKey1, noPrefix)
79
+ ops.push(op)
80
+
81
+ const doc = await data.validateOperationLog(did, ops)
82
+ verifyDoc(doc)
83
+ })
84
+
85
+ it('updates atpPds', async () => {
86
+ const noPrefix = 'example2.com'
87
+ atpPds = `https://${noPrefix}`
88
+ const op = await operations.updatePdsOp(lastOp(), rotationKey1, noPrefix)
89
+ ops.push(op)
90
+
91
+ const doc = await data.validateOperationLog(did, ops)
92
+ verifyDoc(doc)
93
+ })
94
+
95
+ it('rotates signingKey', async () => {
96
+ const newSigningKey = await Secp256k1Keypair.create()
97
+ const op = await operations.updateAtprotoKeyOp(
98
+ lastOp(),
99
+ rotationKey1,
100
+ newSigningKey.did(),
101
+ )
102
+ ops.push(op)
103
+
104
+ signingKey = newSigningKey
105
+
106
+ const doc = await data.validateOperationLog(did, ops)
107
+ verifyDoc(doc)
108
+ })
109
+
110
+ it('rotates rotation keys', async () => {
111
+ const newRotationKey = await Secp256k1Keypair.create()
112
+ const op = await operations.updateRotationKeysOp(lastOp(), rotationKey1, [
113
+ newRotationKey.did(),
114
+ rotationKey2.did(),
115
+ ])
116
+ ops.push(op)
117
+
118
+ oldRotationKey1 = rotationKey1
119
+ rotationKey1 = newRotationKey
120
+
121
+ const doc = await data.validateOperationLog(did, ops)
122
+ verifyDoc(doc)
123
+ })
124
+
125
+ it('no longer allows operations from old rotation key', async () => {
126
+ const op = await operations.updateHandleOp(
127
+ lastOp(),
128
+ oldRotationKey1,
129
+ 'at://bob',
130
+ )
131
+ expect(data.validateOperationLog(did, [...ops, op])).rejects.toThrow(
132
+ InvalidSignatureError,
133
+ )
134
+ })
135
+
136
+ it('does not allow operations from the signingKey', async () => {
137
+ const op = await operations.updateHandleOp(lastOp(), signingKey, 'at://bob')
138
+ expect(data.validateOperationLog(did, [...ops, op])).rejects.toThrow(
139
+ InvalidSignatureError,
140
+ )
141
+ })
142
+
143
+ it('allows for operations from either rotation key', async () => {
144
+ const newHandle = 'at://ali.example.com'
145
+ const op = await operations.updateHandleOp(
146
+ lastOp(),
147
+ rotationKey2,
148
+ newHandle,
149
+ )
150
+ ops.push(op)
151
+ handle = newHandle
152
+ const doc = await data.validateOperationLog(did, ops)
153
+ verifyDoc(doc)
154
+ })
155
+
156
+ it('allows tombstoning a DID', async () => {
157
+ const last = await data.getLastOpWithCid(ops)
158
+ const op = await operations.tombstoneOp(last.cid, rotationKey1)
159
+ const doc = await data.validateOperationLog(did, [...ops, op])
160
+ expect(doc).toBe(null)
161
+ })
162
+
163
+ it('requires operations to be in order', async () => {
164
+ const op = await operations.updateHandleOp(
165
+ ops[ops.length - 2],
166
+ rotationKey1,
167
+ 'at://bob.test',
168
+ )
169
+ expect(data.validateOperationLog(did, [...ops, op])).rejects.toThrow(
170
+ MisorderedOperationError,
171
+ )
172
+ })
173
+
174
+ it('does not allow a create operation in the middle of the log', async () => {
175
+ const op = await operations.atprotoOp({
176
+ signingKey: signingKey.did(),
177
+ rotationKeys: [rotationKey1.did(), rotationKey2.did()],
178
+ handle,
179
+ pds: atpPds,
180
+ prev: null,
181
+ signer: rotationKey1,
182
+ })
183
+ expect(data.validateOperationLog(did, [...ops, op])).rejects.toThrow(
184
+ MisorderedOperationError,
185
+ )
186
+ })
187
+
188
+ it('does not allow a tombstone in the middle of the log', async () => {
189
+ const prev = await cidForCbor(ops[ops.length - 2])
190
+ const tombstone = await operations.tombstoneOp(prev, rotationKey1)
191
+ expect(
192
+ data.validateOperationLog(did, [
193
+ ...ops.slice(0, ops.length - 1),
194
+ tombstone,
195
+ ops[ops.length - 1],
196
+ ]),
197
+ ).rejects.toThrow(MisorderedOperationError)
198
+ })
199
+
200
+ it('requires that the did is the hash of the genesis op', async () => {
201
+ const rest = ops.slice(1)
202
+ expect(data.validateOperationLog(did, rest)).rejects.toThrow(
203
+ GenesisHashError,
204
+ )
205
+ })
206
+
207
+ it('requires that the log starts with a create op (no prev)', async () => {
208
+ const rest = ops.slice(1)
209
+ const expectedDid = await operations.didForCreateOp(rest[0])
210
+ expect(data.validateOperationLog(expectedDid, rest)).rejects.toThrow(
211
+ ImproperOperationError,
212
+ )
213
+ })
214
+ })
@@ -0,0 +1,81 @@
1
+ import * as uint8arrays from 'uint8arrays'
2
+ import { EcdsaKeypair, parseDidKey, Secp256k1Keypair } from '@atproto/crypto'
3
+ import * as document from '../src/document'
4
+ import * as t from '../src/types'
5
+
6
+ describe('document', () => {
7
+ it('formats a valid DID document', async () => {
8
+ const atprotoKey = await Secp256k1Keypair.create()
9
+ const otherKey = await EcdsaKeypair.create()
10
+ const rotate1 = await Secp256k1Keypair.create()
11
+ const rotate2 = await EcdsaKeypair.create()
12
+ const alsoKnownAs = ['at://alice.test', 'https://bob.test']
13
+ const atpPds = 'https://example.com'
14
+ const otherService = 'https://other.com'
15
+ const data: t.DocumentData = {
16
+ did: 'did:example:alice',
17
+ verificationMethods: {
18
+ atproto: atprotoKey.did(),
19
+ other: otherKey.did(),
20
+ },
21
+ rotationKeys: [rotate1.did(), rotate2.did()],
22
+ alsoKnownAs,
23
+ services: {
24
+ atproto_pds: {
25
+ type: 'AtprotoPersonalDataServer',
26
+ endpoint: atpPds,
27
+ },
28
+ other: {
29
+ type: 'SomeService',
30
+ endpoint: otherService,
31
+ },
32
+ },
33
+ }
34
+ const doc = await document.formatDidDoc(data)
35
+ // only expected keys
36
+ expect(Object.keys(doc).sort()).toEqual(
37
+ ['@context', 'id', 'alsoKnownAs', 'verificationMethod', 'service'].sort(),
38
+ )
39
+ expect(doc['@context']).toEqual([
40
+ 'https://www.w3.org/ns/did/v1',
41
+ 'https://w3id.org/security/suites/secp256k1-2019/v1',
42
+ 'https://w3id.org/security/suites/ecdsa-2019/v1',
43
+ ])
44
+ expect(doc.id).toEqual(data.did)
45
+ expect(doc.alsoKnownAs).toEqual(alsoKnownAs)
46
+
47
+ expect(doc.verificationMethod.length).toBe(2)
48
+
49
+ expect(doc.verificationMethod[0].id).toEqual('#atproto')
50
+ expect(doc.verificationMethod[0].type).toEqual(
51
+ 'EcdsaSecp256k1VerificationKey2019',
52
+ )
53
+ expect(doc.verificationMethod[0].controller).toEqual(data.did)
54
+ const parsedAtprotoKey = parseDidKey(atprotoKey.did())
55
+ const atprotoKeyMultibase =
56
+ 'z' + uint8arrays.toString(parsedAtprotoKey.keyBytes, 'base58btc')
57
+ expect(doc.verificationMethod[0].publicKeyMultibase).toEqual(
58
+ atprotoKeyMultibase,
59
+ )
60
+
61
+ expect(doc.verificationMethod[1].id).toEqual('#other')
62
+ expect(doc.verificationMethod[1].type).toEqual(
63
+ 'EcdsaSecp256r1VerificationKey2019',
64
+ )
65
+ expect(doc.verificationMethod[1].controller).toEqual(data.did)
66
+ const parsedOtherKey = parseDidKey(otherKey.did())
67
+ const otherKeyMultibase =
68
+ 'z' + uint8arrays.toString(parsedOtherKey.keyBytes, 'base58btc')
69
+ expect(doc.verificationMethod[1].publicKeyMultibase).toEqual(
70
+ otherKeyMultibase,
71
+ )
72
+
73
+ expect(doc.service.length).toBe(2)
74
+ expect(doc.service[0].id).toEqual('#atproto_pds')
75
+ expect(doc.service[0].type).toEqual('AtprotoPersonalDataServer')
76
+ expect(doc.service[0].serviceEndpoint).toEqual(atpPds)
77
+ expect(doc.service[1].id).toEqual('#other')
78
+ expect(doc.service[1].type).toEqual('SomeService')
79
+ expect(doc.service[1].serviceEndpoint).toEqual(otherService)
80
+ })
81
+ })
@@ -0,0 +1,188 @@
1
+ import { cidForCbor, DAY, HOUR } from '@atproto/common'
2
+ import { EcdsaKeypair, Keypair, Secp256k1Keypair } from '@atproto/crypto'
3
+ import { CID } from 'multiformats/cid'
4
+ import { InvalidSignatureError, LateRecoveryError } from '../src'
5
+ import * as data from '../src/data'
6
+ import * as operations from '../src/operations'
7
+ import * as t from '../src/types'
8
+
9
+ describe('plc recovery', () => {
10
+ let signingKey: Secp256k1Keypair
11
+ let rotationKey1: Secp256k1Keypair
12
+ let rotationKey2: EcdsaKeypair
13
+ let rotationKey3: EcdsaKeypair
14
+ let did: string
15
+ const handle = 'alice.example.com'
16
+ const atpPds = 'https://example.com'
17
+
18
+ let log: t.IndexedOperation[] = []
19
+
20
+ let createCid: CID
21
+
22
+ beforeAll(async () => {
23
+ signingKey = await Secp256k1Keypair.create()
24
+ rotationKey1 = await Secp256k1Keypair.create()
25
+ rotationKey2 = await EcdsaKeypair.create()
26
+ rotationKey3 = await EcdsaKeypair.create()
27
+ })
28
+
29
+ const formatIndexed = async (
30
+ op: t.Operation,
31
+ ): Promise<t.IndexedOperation> => {
32
+ const cid = await cidForCbor(op)
33
+
34
+ return {
35
+ did,
36
+ operation: op,
37
+ cid,
38
+ nullified: false,
39
+ createdAt: new Date(),
40
+ }
41
+ }
42
+
43
+ const signOpForKeys = async (
44
+ keys: Keypair[],
45
+ prev: CID | null,
46
+ signer: Keypair,
47
+ otherChanges: Partial<t.Operation> = {},
48
+ ) => {
49
+ const unsigned = {
50
+ ...operations.formatAtprotoOp({
51
+ signingKey: signingKey.did(),
52
+ rotationKeys: keys.map((k) => k.did()),
53
+ handle,
54
+ pds: atpPds,
55
+ prev,
56
+ }),
57
+ ...otherChanges,
58
+ }
59
+ const op = await operations.addSignature(unsigned, signer)
60
+ const indexed = await formatIndexed(op)
61
+ return { op, indexed }
62
+ }
63
+
64
+ it('creates an op log with rotation', async () => {
65
+ const create = await signOpForKeys(
66
+ [rotationKey1, rotationKey2, rotationKey3],
67
+ null,
68
+ rotationKey1,
69
+ )
70
+ createCid = create.indexed.cid
71
+
72
+ log.push({
73
+ ...create.indexed,
74
+ createdAt: new Date(Date.now() - 7 * DAY),
75
+ })
76
+
77
+ // key 3 tries to usurp control
78
+ const rotate = await signOpForKeys([rotationKey3], createCid, rotationKey3)
79
+
80
+ log.push({
81
+ ...rotate.indexed,
82
+ createdAt: new Date(Date.now() - DAY),
83
+ })
84
+
85
+ // and does some additional ops
86
+ const another = await signOpForKeys(
87
+ [rotationKey3],
88
+ rotate.indexed.cid,
89
+ rotationKey3,
90
+ { alsoKnownAs: ['newhandle.test'] },
91
+ )
92
+
93
+ log.push({
94
+ ...another.indexed,
95
+ createdAt: new Date(Date.now() - HOUR),
96
+ })
97
+ })
98
+
99
+ it('allows a rotation key with higher authority to rewrite history', async () => {
100
+ // key 2 asserts control over key 3
101
+ const rotate = await signOpForKeys([rotationKey2], createCid, rotationKey2)
102
+
103
+ const res = await data.assureValidNextOp(did, log, rotate.op)
104
+ expect(res.nullified.length).toBe(2)
105
+ expect(res.nullified[0].equals(log[1].cid))
106
+ expect(res.nullified[1].equals(log[2].cid))
107
+ expect(res.prev?.equals(createCid)).toBeTruthy()
108
+
109
+ log = [log[0], rotate.indexed]
110
+ })
111
+
112
+ it('does not allow the lower authority key to take control back', async () => {
113
+ const rotate = await signOpForKeys([rotationKey3], createCid, rotationKey3)
114
+ await expect(data.assureValidNextOp(did, log, rotate.op)).rejects.toThrow(
115
+ InvalidSignatureError,
116
+ )
117
+ })
118
+
119
+ it('allows a rotation key with even higher authority to rewrite history', async () => {
120
+ const rotate = await signOpForKeys([rotationKey1], createCid, rotationKey1)
121
+
122
+ const res = await data.assureValidNextOp(did, log, rotate.op)
123
+ expect(res.nullified.length).toBe(1)
124
+ expect(res.nullified[0].equals(log[1].cid))
125
+ expect(res.prev?.equals(createCid)).toBeTruthy()
126
+
127
+ log = [log[0], rotate.indexed]
128
+ })
129
+
130
+ it('does not allow the either invalidated key to take control back', async () => {
131
+ const rotate1 = await signOpForKeys([rotationKey3], createCid, rotationKey3)
132
+ await expect(data.assureValidNextOp(did, log, rotate1.op)).rejects.toThrow(
133
+ InvalidSignatureError,
134
+ )
135
+
136
+ const rotate2 = await signOpForKeys([rotationKey2], createCid, rotationKey2)
137
+ await expect(data.assureValidNextOp(did, log, rotate2.op)).rejects.toThrow(
138
+ InvalidSignatureError,
139
+ )
140
+ })
141
+
142
+ it('does not allow recovery outside of 72 hrs', async () => {
143
+ const rotate = await signOpForKeys([rotationKey3], createCid, rotationKey3)
144
+ const timeOutOps = [
145
+ log[0],
146
+ {
147
+ ...rotate.indexed,
148
+ createdAt: new Date(Date.now() - 4 * DAY),
149
+ },
150
+ ]
151
+ const rotateBack = await signOpForKeys(
152
+ [rotationKey2],
153
+ createCid,
154
+ rotationKey2,
155
+ )
156
+ await expect(
157
+ data.assureValidNextOp(did, timeOutOps, rotateBack.op),
158
+ ).rejects.toThrow(LateRecoveryError)
159
+ })
160
+
161
+ it('allows recovery from a tombstoned DID', async () => {
162
+ const tombstone = await operations.tombstoneOp(createCid, rotationKey2)
163
+ const cid = await cidForCbor(tombstone)
164
+ const tombstoneOps = [
165
+ log[0],
166
+ {
167
+ did,
168
+ operation: tombstone,
169
+ cid,
170
+ nullified: false,
171
+ createdAt: new Date(),
172
+ },
173
+ ]
174
+ const rotateBack = await signOpForKeys(
175
+ [rotationKey1],
176
+ createCid,
177
+ rotationKey1,
178
+ )
179
+ const result = await data.assureValidNextOp(
180
+ did,
181
+ tombstoneOps,
182
+ rotateBack.op,
183
+ )
184
+ expect(result.nullified.length).toBe(1)
185
+ expect(result.nullified[0].equals(cid))
186
+ expect(result.prev?.equals(createCid)).toBeTruthy()
187
+ })
188
+ })
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": ["**/*.spec.ts", "**/*.test.ts"]
4
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist",
6
+ "declarationDir": "./dist",
7
+ "emitDeclarationOnly": true,
8
+ },
9
+ "include": ["./src"]
10
+ }
package/update-pkg.js ADDED
@@ -0,0 +1,14 @@
1
+ const pkgJson = require('@npmcli/package-json')
2
+
3
+ if (process.argv.includes('--update-main-to-dist')) {
4
+ return pkgJson
5
+ .load(__dirname)
6
+ .then((pkg) => pkg.update({ main: 'dist/index.js' }))
7
+ .then((pkg) => pkg.save())
8
+ }
9
+ if (process.argv.includes('--update-main-to-src')) {
10
+ return pkgJson
11
+ .load(__dirname)
12
+ .then((pkg) => pkg.update({ main: 'src/index.ts' }))
13
+ .then((pkg) => pkg.save())
14
+ }