@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,315 @@
1
+ import * as cbor from '@ipld/dag-cbor'
2
+ import { CID } from 'multiformats/cid'
3
+ import * as uint8arrays from 'uint8arrays'
4
+ import { Keypair, parseDidKey, sha256, verifySignature } from '@atproto/crypto'
5
+ import { check, cidForCbor } from '@atproto/common'
6
+ import * as t from './types'
7
+ import {
8
+ GenesisHashError,
9
+ ImproperlyFormattedDidError,
10
+ ImproperOperationError,
11
+ InvalidSignatureError,
12
+ MisorderedOperationError,
13
+ UnsupportedKeyError,
14
+ } from './error'
15
+
16
+ export const didForCreateOp = async (op: t.CompatibleOp, truncate = 24) => {
17
+ const hashOfGenesis = await sha256(cbor.encode(op))
18
+ const hashB32 = uint8arrays.toString(hashOfGenesis, 'base32')
19
+ const truncated = hashB32.slice(0, truncate)
20
+ return `did:plc:${truncated}`
21
+ }
22
+
23
+ // Operations formatting
24
+ // ---------------------------
25
+
26
+ export const formatAtprotoOp = (opts: {
27
+ signingKey: string
28
+ handle: string
29
+ pds: string
30
+ rotationKeys: string[]
31
+ prev: CID | null
32
+ }): t.UnsignedOperation => {
33
+ return {
34
+ type: 'plc_operation',
35
+ verificationMethods: {
36
+ atproto: opts.signingKey,
37
+ },
38
+ rotationKeys: opts.rotationKeys,
39
+ alsoKnownAs: [ensureAtprotoPrefix(opts.handle)],
40
+ services: {
41
+ atproto_pds: {
42
+ type: 'AtprotoPersonalDataServer',
43
+ endpoint: ensureHttpPrefix(opts.pds),
44
+ },
45
+ },
46
+ prev: opts.prev?.toString() ?? null,
47
+ }
48
+ }
49
+
50
+ export const atprotoOp = async (opts: {
51
+ signingKey: string
52
+ handle: string
53
+ pds: string
54
+ rotationKeys: string[]
55
+ prev: CID | null
56
+ signer: Keypair
57
+ }) => {
58
+ return addSignature(formatAtprotoOp(opts), opts.signer)
59
+ }
60
+
61
+ export const createOp = async (opts: {
62
+ signingKey: string
63
+ handle: string
64
+ pds: string
65
+ rotationKeys: string[]
66
+ signer: Keypair
67
+ }): Promise<{ op: t.Operation; did: string }> => {
68
+ const op = await atprotoOp({ ...opts, prev: null })
69
+ const did = await didForCreateOp(op)
70
+ return { op, did }
71
+ }
72
+
73
+ export const createUpdateOp = async (
74
+ lastOp: t.CompatibleOp,
75
+ signer: Keypair,
76
+ fn: (normalized: t.UnsignedOperation) => Omit<t.UnsignedOperation, 'prev'>,
77
+ ): Promise<t.Operation> => {
78
+ const prev = await cidForCbor(lastOp)
79
+ // omit sig so it doesn't accidentally make its way into the next operation
80
+ const { sig, ...normalized } = normalizeOp(lastOp)
81
+ const unsigned = await fn(normalized)
82
+ return addSignature(
83
+ {
84
+ ...unsigned,
85
+ prev: prev.toString(),
86
+ },
87
+ signer,
88
+ )
89
+ }
90
+
91
+ export const updateAtprotoKeyOp = async (
92
+ lastOp: t.CompatibleOp,
93
+ signer: Keypair,
94
+ atprotoKey: string,
95
+ ): Promise<t.Operation> => {
96
+ return createUpdateOp(lastOp, signer, (normalized) => ({
97
+ ...normalized,
98
+ verificationMethods: {
99
+ ...normalized.verificationMethods,
100
+ atproto: atprotoKey,
101
+ },
102
+ }))
103
+ }
104
+
105
+ export const updateHandleOp = async (
106
+ lastOp: t.CompatibleOp,
107
+ signer: Keypair,
108
+ handle: string,
109
+ ): Promise<t.Operation> => {
110
+ const formatted = ensureAtprotoPrefix(handle)
111
+ return createUpdateOp(lastOp, signer, (normalized) => {
112
+ const handleI = normalized.alsoKnownAs.findIndex((h) =>
113
+ h.startsWith('at://'),
114
+ )
115
+ let aka: string[]
116
+ if (handleI < 0) {
117
+ aka = [formatted, ...normalized.alsoKnownAs]
118
+ } else {
119
+ aka = [
120
+ ...normalized.alsoKnownAs.slice(0, handleI),
121
+ formatted,
122
+ ...normalized.alsoKnownAs.slice(handleI + 1),
123
+ ]
124
+ }
125
+ return {
126
+ ...normalized,
127
+ alsoKnownAs: aka,
128
+ }
129
+ })
130
+ }
131
+
132
+ export const updatePdsOp = async (
133
+ lastOp: t.CompatibleOp,
134
+ signer: Keypair,
135
+ endpoint: string,
136
+ ): Promise<t.Operation> => {
137
+ const formatted = ensureHttpPrefix(endpoint)
138
+ return createUpdateOp(lastOp, signer, (normalized) => {
139
+ return {
140
+ ...normalized,
141
+ services: {
142
+ ...normalized.services,
143
+ atproto_pds: {
144
+ type: 'AtprotoPersonalDataServer',
145
+ endpoint: formatted,
146
+ },
147
+ },
148
+ }
149
+ })
150
+ }
151
+
152
+ export const updateRotationKeysOp = async (
153
+ lastOp: t.CompatibleOp,
154
+ signer: Keypair,
155
+ rotationKeys: string[],
156
+ ): Promise<t.Operation> => {
157
+ return createUpdateOp(lastOp, signer, (normalized) => {
158
+ return {
159
+ ...normalized,
160
+ rotationKeys,
161
+ }
162
+ })
163
+ }
164
+
165
+ export const tombstoneOp = async (
166
+ prev: CID,
167
+ key: Keypair,
168
+ ): Promise<t.Tombstone> => {
169
+ return addSignature(
170
+ {
171
+ type: 'plc_tombstone',
172
+ prev: prev.toString(),
173
+ },
174
+ key,
175
+ )
176
+ }
177
+
178
+ // Signing operations
179
+ // ---------------------------
180
+
181
+ export const addSignature = async <T extends Record<string, unknown>>(
182
+ object: T,
183
+ key: Keypair,
184
+ ): Promise<T & { sig: string }> => {
185
+ const data = new Uint8Array(cbor.encode(object))
186
+ const sig = await key.sign(data)
187
+ return {
188
+ ...object,
189
+ sig: uint8arrays.toString(sig, 'base64url'),
190
+ }
191
+ }
192
+
193
+ export const signOperation = async (
194
+ op: t.UnsignedOperation,
195
+ signingKey: Keypair,
196
+ ): Promise<t.Operation> => {
197
+ return addSignature(op, signingKey)
198
+ }
199
+
200
+ // Backwards compatibility
201
+ // ---------------------------
202
+
203
+ export const deprecatedSignCreate = async (
204
+ op: t.UnsignedCreateOpV1,
205
+ signingKey: Keypair,
206
+ ): Promise<t.CreateOpV1> => {
207
+ return addSignature(op, signingKey)
208
+ }
209
+
210
+ export const normalizeOp = (op: t.CompatibleOp): t.Operation => {
211
+ if (check.is(op, t.def.operation)) {
212
+ return op
213
+ }
214
+ return {
215
+ type: 'plc_operation',
216
+ verificationMethods: {
217
+ atproto: op.signingKey,
218
+ },
219
+ rotationKeys: [op.recoveryKey, op.signingKey],
220
+ alsoKnownAs: [ensureAtprotoPrefix(op.handle)],
221
+ services: {
222
+ atproto_pds: {
223
+ type: 'AtprotoPersonalDataServer',
224
+ endpoint: ensureHttpPrefix(op.service),
225
+ },
226
+ },
227
+ prev: op.prev,
228
+ sig: op.sig,
229
+ }
230
+ }
231
+
232
+ // Verifying operations/signatures
233
+ // ---------------------------
234
+
235
+ export const assureValidOp = async (op: t.OpOrTombstone) => {
236
+ if (check.is(op, t.def.tombstone)) {
237
+ return true
238
+ }
239
+ // ensure we support the op's keys
240
+ const keys = [...Object.values(op.verificationMethods), ...op.rotationKeys]
241
+ await Promise.all(
242
+ keys.map(async (k) => {
243
+ try {
244
+ parseDidKey(k)
245
+ } catch (err) {
246
+ throw new UnsupportedKeyError(k, err)
247
+ }
248
+ }),
249
+ )
250
+ if (op.rotationKeys.length > 5) {
251
+ throw new ImproperOperationError('too many rotation keys', op)
252
+ } else if (op.rotationKeys.length < 1) {
253
+ throw new ImproperOperationError('need at least one rotation key', op)
254
+ }
255
+ }
256
+
257
+ export const assureValidCreationOp = async (
258
+ did: string,
259
+ op: t.CompatibleOpOrTombstone,
260
+ ): Promise<t.DocumentData> => {
261
+ if (check.is(op, t.def.tombstone)) {
262
+ throw new MisorderedOperationError()
263
+ }
264
+ const normalized = normalizeOp(op)
265
+ await assureValidOp(normalized)
266
+ await assureValidSig(normalized.rotationKeys, op)
267
+ const expectedDid = await didForCreateOp(op, 64)
268
+ // id must be >=24 chars & prefix is 8chars
269
+ if (did.length < 32) {
270
+ throw new ImproperlyFormattedDidError('too short')
271
+ }
272
+ if (!expectedDid.startsWith(did)) {
273
+ throw new GenesisHashError(expectedDid)
274
+ }
275
+ if (op.prev !== null) {
276
+ throw new ImproperOperationError('expected null prev on create', op)
277
+ }
278
+ const { verificationMethods, rotationKeys, alsoKnownAs, services } =
279
+ normalized
280
+ return { did, verificationMethods, rotationKeys, alsoKnownAs, services }
281
+ }
282
+
283
+ export const assureValidSig = async (
284
+ allowedDids: string[],
285
+ op: t.CompatibleOpOrTombstone,
286
+ ): Promise<string> => {
287
+ const { sig, ...opData } = op
288
+ const sigBytes = uint8arrays.fromString(sig, 'base64url')
289
+ const dataBytes = new Uint8Array(cbor.encode(opData))
290
+ for (const did of allowedDids) {
291
+ const isValid = await verifySignature(did, dataBytes, sigBytes)
292
+ if (isValid) {
293
+ return did
294
+ }
295
+ }
296
+ throw new InvalidSignatureError(op)
297
+ }
298
+
299
+ // Util
300
+ // ---------------------------
301
+
302
+ export const ensureHttpPrefix = (str: string): string => {
303
+ if (str.startsWith('http://') || str.startsWith('https://')) {
304
+ return str
305
+ }
306
+ return `https://${str}`
307
+ }
308
+
309
+ export const ensureAtprotoPrefix = (str: string): string => {
310
+ if (str.startsWith('at://')) {
311
+ return str
312
+ }
313
+ const stripped = str.replace('http://', '').replace('https://', '')
314
+ return `at://${stripped}`
315
+ }
package/src/types.ts ADDED
@@ -0,0 +1,116 @@
1
+ import * as z from 'zod'
2
+ import * as mf from 'multiformats/cid'
3
+
4
+ const cid = z
5
+ .any()
6
+ .refine((obj: unknown) => mf.CID.asCID(obj) !== null, {
7
+ message: 'Not a CID',
8
+ })
9
+ .transform((obj: unknown) => mf.CID.asCID(obj) as mf.CID)
10
+
11
+ const service = z.object({
12
+ type: z.string(),
13
+ endpoint: z.string(),
14
+ })
15
+
16
+ const documentData = z.object({
17
+ did: z.string(),
18
+ rotationKeys: z.array(z.string()),
19
+ verificationMethods: z.record(z.string()),
20
+ alsoKnownAs: z.array(z.string()),
21
+ services: z.record(service),
22
+ })
23
+ export type DocumentData = z.infer<typeof documentData>
24
+
25
+ const unsignedCreateOpV1 = z.object({
26
+ type: z.literal('create'),
27
+ signingKey: z.string(),
28
+ recoveryKey: z.string(),
29
+ handle: z.string(),
30
+ service: z.string(),
31
+ prev: z.null(),
32
+ })
33
+ export type UnsignedCreateOpV1 = z.infer<typeof unsignedCreateOpV1>
34
+ const createOpV1 = unsignedCreateOpV1.extend({ sig: z.string() })
35
+ export type CreateOpV1 = z.infer<typeof createOpV1>
36
+
37
+ const unsignedOperation = z.object({
38
+ type: z.literal('plc_operation'),
39
+ rotationKeys: z.array(z.string()),
40
+ verificationMethods: z.record(z.string()),
41
+ alsoKnownAs: z.array(z.string()),
42
+ services: z.record(service),
43
+ prev: z.string().nullable(),
44
+ })
45
+ export type UnsignedOperation = z.infer<typeof unsignedOperation>
46
+ const operation = unsignedOperation.extend({ sig: z.string() })
47
+ export type Operation = z.infer<typeof operation>
48
+
49
+ const unsignedTombstone = z.object({
50
+ type: z.literal('plc_tombstone'),
51
+ prev: z.string(),
52
+ })
53
+ export type UnsignedTombstone = z.infer<typeof unsignedTombstone>
54
+ const tombstone = unsignedTombstone.extend({ sig: z.string() })
55
+ export type Tombstone = z.infer<typeof tombstone>
56
+
57
+ const opOrTombstone = z.union([operation, tombstone])
58
+ export type OpOrTombstone = z.infer<typeof opOrTombstone>
59
+ const compatibleOp = z.union([createOpV1, operation])
60
+ export type CompatibleOp = z.infer<typeof compatibleOp>
61
+ const compatibleOpOrTombstone = z.union([createOpV1, operation, tombstone])
62
+ export type CompatibleOpOrTombstone = z.infer<typeof compatibleOpOrTombstone>
63
+
64
+ export const indexedOperation = z.object({
65
+ did: z.string(),
66
+ operation: compatibleOpOrTombstone,
67
+ cid: cid,
68
+ nullified: z.boolean(),
69
+ createdAt: z.date(),
70
+ })
71
+ export type IndexedOperation = z.infer<typeof indexedOperation>
72
+
73
+ export const exportedOp = z.object({
74
+ did: z.string(),
75
+ operation: compatibleOpOrTombstone,
76
+ cid: z.string(),
77
+ nullified: z.boolean(),
78
+ createdAt: z.string(),
79
+ })
80
+ export type ExportedOp = z.infer<typeof exportedOp>
81
+
82
+ export const didDocVerificationMethod = z.object({
83
+ id: z.string(),
84
+ type: z.string(),
85
+ controller: z.string(),
86
+ publicKeyMultibase: z.string(),
87
+ })
88
+
89
+ export const didDocService = z.object({
90
+ id: z.string(),
91
+ type: z.string(),
92
+ serviceEndpoint: z.string(),
93
+ })
94
+
95
+ export const didDocument = z.object({
96
+ '@context': z.array(z.string()),
97
+ id: z.string(),
98
+ alsoKnownAs: z.array(z.string()),
99
+ verificationMethod: z.array(didDocVerificationMethod),
100
+ service: z.array(didDocService),
101
+ })
102
+ export type DidDocument = z.infer<typeof didDocument>
103
+
104
+ export const def = {
105
+ documentData,
106
+ createOpV1,
107
+ unsignedOperation,
108
+ operation,
109
+ tombstone,
110
+ opOrTombstone,
111
+ compatibleOp,
112
+ compatibleOpOrTombstone,
113
+ indexedOperation,
114
+ exportedOp,
115
+ didDocument,
116
+ }
@@ -0,0 +1,89 @@
1
+ import { cidForCbor, DAY } from '@atproto/common'
2
+ import { Secp256k1Keypair } from '@atproto/crypto'
3
+ import {
4
+ assureValidNextOp,
5
+ CreateOpV1,
6
+ deprecatedSignCreate,
7
+ didForCreateOp,
8
+ normalizeOp,
9
+ updateRotationKeysOp,
10
+ updateAtprotoKeyOp,
11
+ validateOperationLog,
12
+ } from '../src'
13
+
14
+ describe('compatibility', () => {
15
+ let signingKey: Secp256k1Keypair
16
+ let recoveryKey: Secp256k1Keypair
17
+ const handle = 'alice.test'
18
+ const service = 'https://example.com'
19
+ let did: string
20
+
21
+ let legacyOp: CreateOpV1
22
+
23
+ beforeAll(async () => {
24
+ signingKey = await Secp256k1Keypair.create()
25
+ recoveryKey = await Secp256k1Keypair.create()
26
+ })
27
+
28
+ it('normalizes legacy create ops', async () => {
29
+ legacyOp = await deprecatedSignCreate(
30
+ {
31
+ type: 'create',
32
+ signingKey: signingKey.did(),
33
+ recoveryKey: recoveryKey.did(),
34
+ handle,
35
+ service,
36
+ prev: null,
37
+ },
38
+ signingKey,
39
+ )
40
+
41
+ did = await didForCreateOp(legacyOp)
42
+
43
+ const normalized = normalizeOp(legacyOp)
44
+ expect(normalized).toEqual({
45
+ type: 'plc_operation',
46
+ verificationMethods: {
47
+ atproto: signingKey.did(),
48
+ },
49
+ rotationKeys: [recoveryKey.did(), signingKey.did()],
50
+ alsoKnownAs: [`at://${handle}`],
51
+ services: {
52
+ atproto_pds: {
53
+ type: 'AtprotoPersonalDataServer',
54
+ endpoint: service,
55
+ },
56
+ },
57
+ prev: null,
58
+ sig: legacyOp.sig,
59
+ })
60
+ })
61
+
62
+ it('validates a log with a legacy create op', async () => {
63
+ const legacyCid = await cidForCbor(legacyOp)
64
+ const newSigner = await Secp256k1Keypair.create()
65
+ const newRotater = await Secp256k1Keypair.create()
66
+ const nextOp = await updateAtprotoKeyOp(
67
+ legacyOp,
68
+ signingKey,
69
+ newSigner.did(),
70
+ )
71
+ const anotherOp = await updateRotationKeysOp(nextOp, signingKey, [
72
+ newRotater.did(),
73
+ ])
74
+ await validateOperationLog(did, [legacyOp, nextOp])
75
+ await validateOperationLog(did, [legacyOp, nextOp, anotherOp])
76
+
77
+ const indexedLegacy = {
78
+ did,
79
+ operation: legacyOp,
80
+ cid: legacyCid,
81
+ nullified: false,
82
+ createdAt: new Date(Date.now() - 7 * DAY),
83
+ }
84
+
85
+ const result = await assureValidNextOp(did, [indexedLegacy], nextOp)
86
+ expect(result.nullified.length).toBe(0)
87
+ expect(result.prev?.equals(legacyCid)).toBeTruthy()
88
+ })
89
+ })